본문 바로가기
LeetCode

[LeetCode] 70. Climbing Stairs

by JungSeung 2024. 2. 23.
728x90

https://leetcode.com/

 

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

Code:

var climbStairs = function(n) {
    if (n === 1) return 1; // 만약 n이 1이라면 1을 반환
    let dp = new Array(n + 1).fill(0); // 길이가 n+1이고 0으로 채워진 배열 dp 생성
    dp[1] = 1; // 첫 번째 요소를 1로 설정
    dp[2] = 2; // 두 번째 요소를 2로 설정
    for (let i = 3; i <= n; i++) {
        dp[i] = dp[i - 1] + dp[i - 2]; // dp의 각 요소를 이전 두 요소의 합으로 설정
    }
    return dp[n]; // 마지막 요소 반환
};

 

출처 : https://leetcode.com/problemset/all/

 

Problems - LeetCode

Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.

leetcode.com

 

728x90

'LeetCode' 카테고리의 다른 글

[LeetCode] 72. Edit Distance  (0) 2024.03.01
[LeetCode] 71. Simplify Path  (0) 2024.02.27
[LeetCode] 69. Sqrt(x)  (0) 2024.02.23
[LeetCode] 68. Text Justification  (0) 2024.02.19
[LeetCode] 67. Add Binary  (0) 2024.01.30