Skip to content

Commit ac9036a

Browse files
feat : climbing-stairs
1 parent 1473988 commit ac9036a

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// dfs๋ฅผ ์ด์šฉํ•œ ํ’€์ด
2+
// dp ๋ฐฐ์—ด์„ ์ด์šฉํ•œ ๊ฒƒ๋ณด๋‹ค ๊ณต๊ฐ„๋ณต์žก๋„๊ฐ€ ์ƒ๋Œ€์ ์œผ๋กœ ๋‚ฎ๊ฒŒ ์žกํž˜ 40.4mb -> 40.1mb
3+
// ์ด์œ ๊ฐ€ ๋ญ”์ง€๋Š” ์กฐ๊ธˆ ๋” ๊ณ ๋ฏผํ•ด๋ด์•ผํ•  ๋“ฏ
4+
class Solution {
5+
public int climbStairs(int n) {
6+
return dfs(n, new HashMap<>());
7+
}
8+
9+
private int dfs(int n, Map<Integer, Integer> memo) {
10+
if (n == 0) {
11+
return 1;
12+
}
13+
if (n < 0) {
14+
return 0;
15+
}
16+
if (memo.containsKey(n)) {
17+
return memo.get(n);
18+
}
19+
20+
int result = dfs(n - 1, memo) + dfs(n - 2, memo);
21+
memo.put(n, result);
22+
23+
return result;
24+
}
25+
}
26+
27+
// ๊ฐ€์žฅ ๋จผ์ € ์ƒ๊ฐํ•œ ํ’€์ด
28+
// ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด์˜ ํ˜•ํƒœ์˜ ๊ฒฐ๊ณผ๋ฌผ์„ ๊ฐ–๋Š”๋‹ค.
29+
// O(N)์˜ ์ ํ™”์‹์„ ์„ธ์šธ ์ˆ˜ ์žˆ์œผ๋ฉด ์–ด๋А ๋ฐฉ์‹์œผ๋กœ๋„ ํ’€๋ฆผ
30+
class Solution {
31+
public int climbStairs(int n) {
32+
if(n == 1) return 1;
33+
if(n == 2) return 2;
34+
35+
int[] dp = new int[n + 1];
36+
dp[1] = 1; // 1
37+
dp[2] = 2; // 1+1, 2
38+
39+
for (int i = 3; i <= n; i++) {
40+
dp[i] = dp[i-1] + dp[i-2];
41+
}
42+
43+
return dp[n];
44+
}
45+
}

0 commit comments

Comments
ย (0)