Skip to content

Commit

Permalink
feat : climbing-stairs
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielDonghaKim committed Dec 17, 2024
1 parent 1473988 commit ac9036a
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions climbing-stairs/imsosleepy.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// dfs๋ฅผ ์ด์šฉํ•œ ํ’€์ด
// dp ๋ฐฐ์—ด์„ ์ด์šฉํ•œ ๊ฒƒ๋ณด๋‹ค ๊ณต๊ฐ„๋ณต์žก๋„๊ฐ€ ์ƒ๋Œ€์ ์œผ๋กœ ๋‚ฎ๊ฒŒ ์žกํž˜ 40.4mb -> 40.1mb
// ์ด์œ ๊ฐ€ ๋ญ”์ง€๋Š” ์กฐ๊ธˆ ๋” ๊ณ ๋ฏผํ•ด๋ด์•ผํ•  ๋“ฏ
class Solution {
public int climbStairs(int n) {
return dfs(n, new HashMap<>());
}

private int dfs(int n, Map<Integer, Integer> memo) {
if (n == 0) {
return 1;
}
if (n < 0) {
return 0;
}
if (memo.containsKey(n)) {
return memo.get(n);
}

int result = dfs(n - 1, memo) + dfs(n - 2, memo);
memo.put(n, result);

return result;
}
}

// ๊ฐ€์žฅ ๋จผ์ € ์ƒ๊ฐํ•œ ํ’€์ด
// ํ”ผ๋ณด๋‚˜์น˜ ์ˆ˜์—ด์˜ ํ˜•ํƒœ์˜ ๊ฒฐ๊ณผ๋ฌผ์„ ๊ฐ–๋Š”๋‹ค.
// O(N)์˜ ์ ํ™”์‹์„ ์„ธ์šธ ์ˆ˜ ์žˆ์œผ๋ฉด ์–ด๋Š ๋ฐฉ์‹์œผ๋กœ๋„ ํ’€๋ฆผ
class Solution {
public int climbStairs(int n) {
if(n == 1) return 1;
if(n == 2) return 2;

int[] dp = new int[n + 1];
dp[1] = 1; // 1
dp[2] = 2; // 1+1, 2

for (int i = 3; i <= n; i++) {
dp[i] = dp[i-1] + dp[i-2];
}

return dp[n];
}
}

0 comments on commit ac9036a

Please sign in to comment.