Skip to content

Commit b1ebca8

Browse files
committed
Chapter 09 section 02 C++ codes updated. Java codes added.
1 parent 9ad390b commit b1ebca8

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import java.util.Arrays;
2+
3+
/**
4+
* Created by liuyubobobo.
5+
*/
6+
public class Solution1 {
7+
8+
private int[] memo;
9+
10+
public int climbStairs(int n) {
11+
memo = new int[n+1];
12+
Arrays.fill(memo, -1);
13+
return calcWays(n);
14+
}
15+
16+
private int calcWays(int n){
17+
18+
if(n == 0 || n == 1)
19+
return 1;
20+
21+
if(memo[n] == -1)
22+
memo[n] = calcWays(n - 1) + calcWays(n - 2);
23+
24+
return memo[n];
25+
}
26+
27+
public static void main(String[] args) {
28+
29+
System.out.println((new Solution1()).climbStairs(10));
30+
}
31+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/// 70. Climbing Stairs
2+
/// https://leetcode.com/problems/climbing-stairs/description/
3+
/// 动态规划
4+
/// 时间复杂度: O(n)
5+
/// 空间复杂度: O(n)
6+
public class Solution2 {
7+
8+
public int climbStairs(int n) {
9+
10+
int[] memo = new int[n + 1];
11+
memo[0] = 1;
12+
memo[1] = 1;
13+
for(int i = 2 ; i <= n ; i ++)
14+
memo[i] = memo[i - 1] + memo[i - 2];
15+
return memo[n];
16+
}
17+
18+
public static void main(String[] args) {
19+
20+
System.out.println((new Solution2()).climbStairs(10));
21+
}
22+
}

0 commit comments

Comments
 (0)