LeetCode Climbing Stairs (JavaScript)

2025. 12. 8. 13:15·코딩테스트/LeetCode

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

문제 설명

더보기

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

문제 풀이

DFS를 이용하여 모든 경우의 수를 구하려고하면 시간 초과 오류가 발생

이 문제는 Combination을 이용하여 풀어야 함

즉, 1과 2를 선택한 갯수에 따른 조합 갯수를 구하면 됨.

(총 자릿수 n, 2 선택 갯수 r -> nCr을 구하면 됨)

e.g. n = 6인 경우

1이 6개, 2가 0개인 경우 -> 6C0 -> 1

1이 4개, 2가 1개인 경우 -> 5C1 -> 5

1이 2개, 2가 2개인 경우 -> 4C2 -> 6

1이 0개, 2가 3개인 경우 -> 3C3 -> 1

/**
 * @param {number} n
 * @return {number}
 */
var climbStairs = function(n) {
    const getCombination = (n, r) => {
        let result = 1;

        if (r < 0 || r > n) {
            return 0;
        }
        if (r === 0 || r === n) {
            return 1;
        }

        for (let i = 1; i <= r; i++) {
            result *= (n - i + 1);
            result /= i;
        }

        return Math.round(result);
    }

    let k = 0;
    let answer = 0;
    while (2 * k <= n) {
        const nn = n - k;

        answer += getCombination(nn, k);

        k += 1;
    }

    return answer;
};

결론

규칙성을 찾고 해당 규칙을 로직으로 구현하면 됨(이 문제는 조합을 구하는 규칙을 찾는게 핵심)

'코딩테스트 > LeetCode' 카테고리의 다른 글

LeetCode Pascal's Triangle (JavaScript)  (0) 2025.12.09
LeetCode Remove Duplicates from Sorted List (JavaScript)  (0) 2025.12.09
LeetCode Sqrt(x) (JavaScript)  (1) 2025.12.08
LeetCode Add Binary (JavaScript)  (0) 2025.11.27
LeetCode Plus One (JavaScript)  (0) 2025.11.27
'코딩테스트/LeetCode' 카테고리의 다른 글
  • LeetCode Pascal's Triangle (JavaScript)
  • LeetCode Remove Duplicates from Sorted List (JavaScript)
  • LeetCode Sqrt(x) (JavaScript)
  • LeetCode Add Binary (JavaScript)
의현
의현
개발하는 하루
  • 의현
    UIHYEON
    의현
  • 링크

    • 김의현 포트폴리오
    • GitHub
    • LinkedIn
  • 전체
    오늘
    어제
    • 분류 전체보기 (215) N
      • 프론트엔드 (65) N
        • JavaScript (52) N
        • HTML (3)
        • React (7)
        • CSS (2)
        • CS (1)
      • 프로젝트 (19)
        • Portfolio 사이트 개발 (19)
      • 코딩테스트 (128) N
        • Binary Search (2)
        • bfs (Breadth-first s.. (4)
        • dfs (Deapth-first se.. (1)
        • Greedy (1)
        • Dynamic Programming (1)
        • two pointer (4)
        • 구현 (2)
        • LIS(Longest Increasi.. (0)
        • 문자열 (3)
        • 자료구조 (6)
        • 비트마스크 (2)
        • 수학 (2)
        • 프로그래머스 (61)
        • LeetCode (39) N
  • 인기 글

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
의현
LeetCode Climbing Stairs (JavaScript)
상단으로

티스토리툴바