Leetcode
Dynamic Programming
70 Climbing Stairs

1. Question

You are climbing a stair case. It takesnsteps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note:Given n will be a positive integer.
Example 1:
1
Input: 2
2
3
Output: 2
4
5
Explanation:
6
There are two ways to climb to the top.
7
8
1. 1 step + 1 step
9
2. 2 steps
Copied!
Example 2:
1
Input: 3
2
3
Output: 3
4
5
Explanation:
6
There are three ways to climb to the top.
7
8
1. 1 step + 1 step + 1 step
9
2. 1 step + 2 steps
10
3. 2 steps + 1 step
Copied!

2. Implementation

(1) DP
1
public class Solution {
2
public int climbStairs(int n) {
3
if (n <= 2) {
4
return n;
5
}
6
7
int[] step = new int[n + 1];
8
9
step[0] = 0;
10
step[1] = 1;
11
step[2] = 2;
12
13
for (int i = 3; i <= n; i++) {
14
step[i] = step[i - 1] + step[i - 2];
15
}
16
return step[n];
17
}
18
}
Copied!

3. Time & Space Complexity

时间复杂度O(n), 空间复杂度O(n)