[LeetCode] Climbing Stairs
https://leetcode.com/problems/climbing-stairs/
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
This was an easy-level problem.
I think it can be solved quickly once you identify the pattern.
Easy 난이도 문제였다.
사실 규칙만 찾으면 금방 풀 수 있는 문제라고 생각한다.
The number of ways to climb n stairs is the sum of the ways to climb n − 1 stairs and n − 2 stairs.
To reach the n-th stair, you must come from either one step below or two steps below.
Therefore, adding the number of ways to reach n − 1 and n − 2 gives the number of ways to reach n.
n개의 계단을 오르는 방법은 n-1개의 계단을 오르는 방법과 n-2개의 계단을 오르는 방법을 더한 값과 같다.
n번째 계단을 오르기 위해서는 n번째 계단의 2칸 아래 또는 1칸 아래에 이미 도착한 상태에서 2칸 또는 1칸을 올라야 한다.
그러니까... n-1칸과 n-2칸까지 올라가는 수를 더하면 n칸을 올라가는 방법의 수가 되는 것이다.
And this is exactly the Fibonacci sequence.
그리고 이건 피보나치 수열과 동일함!
class Solution {
public int climbStairs(int n) {
// same with fibonacci
if(n > 2){
int[] resArr = new int[n];
resArr[0] = 1;
resArr[1] = 2;
for(int i=2; i<n; i++){
resArr[i] = resArr[i-1]+resArr[i-2];
}
return resArr[n-1];
}else{
return n;
}
}
}
그대로 구현만 하면 끝~
'CodingTest' 카테고리의 다른 글
| [LeetCode] 3Sum (0) | 2025.12.04 |
|---|---|
| [LeetCode] Valid Anagram (0) | 2025.11.24 |
| [LeetCode] Longest Consecutive Sequence (0) | 2025.11.21 |




