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) {
if (n < 2) {
return 1;
}
let firstStep = 1;
let secondStep = 1;
let thirdStep = 0;
for (let i=2; i<=n; i++) {
thirdStep = firstStep + secondStep;
firstStep = secondStep;
secondStep = thirdStep;
}
return thirdStep;
};
'코딩 테스트 풀이 🛠' 카테고리의 다른 글
[프로그래머스] JadenCase 문자열 만들기 (0) | 2023.02.28 |
---|---|
[Leet Code - midium] 08. String to Integer (atoi) (0) | 2023.02.28 |
[Leet Code - eazy] 69. Sqrt(x) (0) | 2023.02.22 |
[프로그래머스] 피보나치 수 (0) | 2023.02.22 |
[프로그래머스] 올바른 괄호 (0) | 2023.02.22 |