huequad / swift-algorithm

1 stars 0 forks source link

70. Climbing Stairs #18

Closed lenaios closed 3 years ago

lenaios commented 3 years ago

https://leetcode.com/problems/climbing-stairs/description

zekexros commented 3 years ago

https://github.com/zeke-iOS/AlgorithmPractice/blob/main/LeetCode/Leet-70.swift

lenaios commented 3 years ago

이전 계단에서 +1칸 오르기, 이전전 계단에서 +2칸 오르기 = 즉, 이전 단계와 이전전 단계까지 올 수 있는 경우의 수 합 구하기(메모이제이션)

class Solution {
    func climbStairs(_ n: Int) -> Int {
        if n <= 2 { return n }
        var prev = 2
        var pprev = 1
        var k = 3
        while k < n + 1 {
            let current = pprev + prev
            pprev = prev
            prev = current
            k += 1
        }
        return prev
    }
}