๐ก LeetCode 70 - Climbing Stairs
๐ก LeetCode 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 howmany distinct ways can you climb to the top?
์ ์ถ๋ ฅ ์์
โ ์์ 1
1
2
3
4
5
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
โ ์์ 2
1
2
3
4
5
6
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
์ ์ฝ์กฐ๊ฑด
1ย <=ย nย <=ย 45
์์ฑ ์ฝ๋
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int climbStairs(int n) {
// 1. ์ ํจ์ฑ ์ฒดํฌ ๋ฐ ๋ฐํ
if (n == 1) return 1;
// 2. ๋ฐฐ์ด ์ ์ธ ๋ฐ ์ด๊ธฐํ
int[] dp = new int[n + 1];
dp[1] = 1;
dp[2] = 2;
// 3. DP ์ฒ๋ฆฌ
for (int i=3; i<=n; i++) {
dp[i] = dp[i - 2] + dp[i - 1];
}
// 4. ๋ฐํ
return dp[n];
}
}
- ์ ํ์์ ๋ค์๊ณผ ๊ฐ๋ค.
1
f(n) = f(n - 1) + f(n - 2)
ํ๊ณ
DP
๋ ์์ ๋ฌธ์ ๋ค์ ๋ต์ ์กฐํฉํด์ ํฐ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๋ ๋ฐฉ์์ด๋ค.- ๋ฌธ์ ๋ฅผ ์์ ๋ฌธ์ ๋ก ๋๋ ๋ ์ค๋ณต ๊ณ์ฐ์ ์ค์ผ ์ ์๋๋ก ๊ฐ์ ์ฌ์ฌ์ฉ ํด์ผ ํ๋ค.
This post is licensed under CC BY 4.0 by the author.