Johnlin
July 04, 2017

# Swift Warmup climb stairs

July 04, 2017

## Transcript

2. ### 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 ੋਖ਼੔Ꮠ
3. ### ൣྫ • n = 4 • 1,1,1,1  1,1,2  1,2,1  2,1,1

2,2 • ڞ༗ 5 छᗡ๏
4. ### ൣྫ • 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 छᗡ๏

{ } }
6. ### ԋࢉ๏ • Ҏޒ֊ᒭఐҝྫɼ༗Մೳੋኺୈ࢛֊૸Ұ㑊্ိɼ໵ ༗Մೳੋኺୈࡾ֊૸ၷ㑊্ိɻ • ࣕୈ࢛֊༗Մೳੋኺୈೋ֊҃ୈࡾ֊ᗡ্ိɻ • ୈࡾ֊༗ՄೳੋኺୈҰ֊҃ୈೋ֊ᗡ্ိɻ • ୈೋ֊༗Մೳੋኺୈྵ֊҃ୈҰ֊ᗡ্ိɻ

• ୈҰ֊୞ೳኺୈྵ֊ᗡ্ိɻ
7. ### ԋࢉ๏ 5 4 3 3 2 2 2 1 1

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

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

guard n > 1 else { return 1} let ans = climbStairs(n-1) + climbStairs(n-2) return ans } }
10. ### 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

12. ### 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

14. ### 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

16. ### 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Ꮣຫྃ