๋์ด๋: Easy
ํค์๋: DP
๐ ๋ฌธ์
๊ณ๋จ์ ์ค๋ฅด๊ณ ์์ต๋๋ค. ๊ผญ๋๊ธฐ์ ๋๋ฌํ๊ธฐ ์ํด n๊ฐ์ ๋จ๊ณ๊ฐ ํ์ํฉ๋๋ค.
๊ฐ ๋จ๊ณ๋ง๋ค 1๊ฐ ๋๋ 2๊ฐ์ ๋จ๊ณ๋ฅผ ์ค๋ฅผ ์ ์์ต๋๋ค. ๊ผญ๋๊ธฐ์ ๋๋ฌํ๋ ๋ฐ ๋ช ๊ฐ์ง ๋ค๋ฅธ ๋ฐฉ๋ฒ์ด ์๋์ง ๊ณ์ฐํ์ธ์.
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
๋ฌธ์ ์๋ฌธ: https://leetcode.com/problems/climbing-stairs/description/
๐ ๋ฌธ์ ํ์ด
๊ธฐ๋ณธ์ ์ธ DP ๋ฌธ์ ์ด๋ค. ๋ฌธ์ ๋ฅผ ์ฌ๊ท ํจ์๋ก ํํํ ์ ์๋์ง๋ฅผ ํ์ ํ ํ Top-down. ํน์ Bottom-up ๋ฐฉ์์ผ๋ก ํด๋ฅผ ์ฐพ์ ์ ์๋ค.
์ผ๋ฐ์ ์ผ๋ก Bottom-up์ด ๋ ๋น ๋ฅด๊ธฐ ๋๋ฌธ์ bottom up์ผ๋ก ์ฝ๋๋ฅผ ์งฐ๋ค.
a[n]์ n๋ฒ์งธ ๊ณ๋จ๊น์ง ๊ฐ๋ ๋ฐ ๊ฐ๋ฅํ ๋ฐฉ๋ฒ ์๋ผ๊ณ ํ๋ฉด
a[n] = a[n-2] + a[n-1]์ ๋ง์กฑํ๋ฏ๋ก
class Solution {
public:
int climbStairs(int n) {
vector<int> a(n+1, 0);
if(n == 1) return 1;
if(n == 2) return 2;
a[0] = 1;
a[1] = 1;
a[2] = 2;
for(auto i = 3; i < (n+1); ++i){
a[i] = a[i-1] + a[i-2];
}
return a[n];
}
};
'IN DEPTH CAKE > Supercoder' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[c++/LeetCode-DP] 91. Decode Ways (w/ DP ํ์ด ์ ๋ต) (3) | 2024.05.06 |
---|---|
[c++/LeetCode-DP] 746. Min Cost Climbing Stairs (1) | 2024.05.06 |
[c++/LeetCode-Hash Table] 939. Minimum Area Rectangle (1) | 2024.05.05 |
[c++/LeetCode-Hash Table] 692. Top K Frequent Words (1) | 2024.05.05 |
[c++/LeetCode-Hash Table] 387. First Unique Character in a String (1) | 2024.05.05 |