반응형
SMALL
문제
You are climbing a staircase. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: n = 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
Constraints:
- 1 <= n <= 45
코드
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function(n) {
const memo = new Map();
const method = (num) => {
if(!num) return 0;
if(num === 1) return 1;
if(num === 2) return 2;
if(memo.has(num)) return memo.get(num)
let result = method(num - 1) + method(num - 2);
memo.set(num, result);
return result;
}
return method(n);
};
반응형
LIST
'Coding Interview' 카테고리의 다른 글
3-4. [구간합] 구간 합 구하기 2 (0) | 2023.01.23 |
---|---|
[LeetCode] DP, DFS - 62. Unique Paths (0) | 2022.10.05 |
[LeetCode] DP - 55. Jump Game (0) | 2022.10.05 |
[LeetCode] DP, BFS - 139. Word Break (0) | 2022.10.05 |
[LeetCode] DP - 121. Best Time to Buy and Sell Stock (0) | 2022.10.04 |