π‘ 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.