Skip to content

Commit 8ad991f

Browse files
committed
climbing stairs solution
1 parent e832a64 commit 8ad991f

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

โ€Žclimbing-stairs/Yn3-3xh.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
[๋ฌธ์ œํ’€์ด]
3+
- 1 ๋˜๋Š” 2๋กœ n์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์ „์ฒด ๊ฐ€์ง€์ˆ˜ ๊ตฌํ•˜๊ธฐ
4+
- dfs (X) ์‹œ๊ฐ„์ดˆ๊ณผ
5+
class Solution {
6+
7+
public int climbStairs(int n) {
8+
return dfs(n);
9+
}
10+
11+
private int dfs(int n) {
12+
if (n == 0) {
13+
return 1;
14+
}
15+
if (n < 0) {
16+
return 0;
17+
}
18+
return dfs(n - 1) + dfs(n - 2);
19+
}
20+
}
21+
22+
- DP (O)
23+
time: O(N), space: O(1)
24+
25+
[ํšŒ๊ณ ]
26+
๊ทœ์น™์„ ์ฐพ์œผ๋ ค๊ณ  ํ–ˆ์—ˆ๋Š”๋ฐ ๋ชป์ฐพ์•˜๋‹ค..
27+
ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด.. ํ’€์—ˆ๋˜ ๋ฌธ์ œ์ธ๋ฐ.. ์ƒ๊ฐํ•˜์ž;
28+
F(N) = F(n-1) + F(n-2)
29+
*/
30+
class Solution {
31+
32+
public int climbStairs(int n) {
33+
if (n <= 3) {
34+
return n;
35+
}
36+
37+
int prev1 = 3;
38+
int prev2 = 2;
39+
int current = 0;
40+
for (int i = 4; i <= n; i++) {
41+
current = prev1 + prev2;
42+
prev2 = prev1;
43+
prev1 = current;
44+
}
45+
return current;
46+
}
47+
}

0 commit comments

Comments
ย (0)