Post

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