Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Swift Warmup climb stairs

Sponsored · Your Podcast. Everywhere. Effortlessly. Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.

Swift Warmup climb stairs

Avatar for Johnlin

Johnlin

July 04, 2017
Tweet

More Decks by Johnlin

Other Decks in Programming

Transcript

  1. Climb Stairs • https://leetcode.com/problems/climbing-stairs/ • You are climbing a stair

    case. It takes n steps to reach to the top.
 Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
 Note: Given n will be a positive integer. • 㟬ࡏᗡఐࢠɼཁᗡ̣㑊࠽။౸௖ɻ
 㟬Ұ࣍ՄҎᗡҰ֨҃ၷ֨ɼ㟬༗زछՄೳతᗡ๏䏆ʁ
 PS. N ੋਖ਼੔Ꮠ
  2. ൣྫ • n = 5 • 1,1,1,1,1
 1,1,1,2
 1,1,2,1
 1,2,1,1


    2,1,1,1
 2,2,1
 2,1,2
 1,2,1 • ڞ༗ 8 छᗡ๏
  3. ԋࢉ๏ 5 4 3 3 2 2 2 1 1

    1 1 0 0 0 0 0 0 1 0
  4. ԋࢉ๏ • ୈN֊తՄೳ૸๏Ꮠ= ୈN - 1֊తՄೳ૸๏Ꮠ + 
 ୈN -

    2֊తՄೳ૸๏Ꮠ
 ୈҰ֊࿨ୈྵ֊౎୞༗Ұछ૸๏ • F(n) = F(n-1) + F(n-2) • F(0) = 1 • F(1) = 1
  5. class Solution { func climbStairs(_ n: Int) -> Int {

    guard n > 1 else { return 1} let ans = climbStairs(n-1) + climbStairs(n-2) return ans } }
  6. class Solution { func climbStairs(_ n: Int) -> Int {

    guard n > 1 else { return 1} let ans = climbStairs(n-1) + climbStairs(n-2) return ans } } ࣌ؒෳᯑ౓: O(2^N)
 ۭؒෳᯑ౓: O(2^N) ࢉෆ׬ OTL
  7. class Solution { var memo:[Int:Int] = [:] func climbStairs(_ n:

    Int) -> Int { guard n > 1 else { return 1} guard memo[n] == nil else { return memo[n]! } let ans = climbStairs(n-1) + climbStairs(n-2) memo[n] = ans return ans } } ࣌ؒෳᯑ౓: O(N)
 ۭؒෳᯑ౓: O(N) 32 ms
  8. class Solution { func climbStairs(_ n: Int) -> Int {

    guard n > 1 else { return 1} var big = 1 var small = 1 for i in 2...n { let sum = big + small small = big big = sum } return big } } ࣌ؒෳᯑ౓: O(N)
 ۭؒෳᯑ౓: O(N) 16 ms
  9. class Solution01 { func climbStairs(_ n: Int) -> Int {

    let nd : Double = Double(n+1) let sqrt5 = sqrt(5) let ans = ( pow((1+sqrt5)/2, nd) - pow((1- sqrt5)/2, nd) ) / sqrt5 return Int(ans.rounded()) } } ࣌ؒෳᯑ౓: O(1)
 ۭؒෳᯑ౓: O(1) 48 ms XDDᏓຫྃ
  10. Q&A