문제
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.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
풀이
중복 계산을 제거하도록 memoization을 사용합니다.
class Solution:
cache = {}
def climbStairs(self, n: int) -> int:
if n < 3:
return n
else :
return self._climbStairs(n-1) + self._climbStairs(n-2)
def _climbStairs(self, n: int):
if n not in self.cache.keys() :
self.cache[n] = self.climbStairs(n)
return self.cache[n]
'알고리즘 트레이닝 > LeetCode' 카테고리의 다른 글
21. Merge Two Sorted Lists (0) | 2020.05.09 |
---|---|
83. Remove Duplicates from Sorted List (0) | 2020.05.09 |
69. Sqrt(x) (0) | 2020.05.08 |
58. Length of Last Word (0) | 2020.05.08 |
35. Search Insert Position (0) | 2020.05.07 |