컴퓨터/Leet me code
Leet me code 5 - [LeetCode][C++] 70. Climbing Stairs (Easy)
정대2
2022. 2. 25. 23:21
leet code me :-|
https://leetcode.com/problems/climbing-stairs/
Climbing Stairs - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
70. 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
문제 정리
계단 오르는 방법 구하기! (다이나믹 프로그래밍)
계단은 한번에 한 칸 또는 두 칸 올라갈 수 있고, N 번째 계단에서 오르는 방법을 구한다.
생각의 흐름
dp[] 배열에 N번 째 계단에 오를 수 있는 방법을 저장
... | i-2 | i-1 | i | ... |
2-> | ||||
1 -> |
한 번에 한 칸 또는 두 칸 올라갈 수 있기때문에, i번 째 칸에 오르려면
i-2번 째 계단에서 두 칸을 오르거나, i-1번 째 계단에서 한 칸을 올라야 한다.
i-2/i-1번 째 계단까지 오르는 방법을 알면 i번 째 계단에 오르는 방법을 구할 수 있다.
Solution 코드
class Solution {
public:
int climbStairs(int n) {
if (n < 3) return n;
vector<int> dp(n+1, 1);
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; ++i) {
dp[i] = dp[i-2] + dp[i-1];
}
return dp[n];
}
};