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.