问题:
You are climbing a stair case. It takes n steps 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:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
Example 2:
Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step
解决:
① 使用递归的方法暴力破解,超时。当前为第i层,最终要求到达第n层。
climbStairs(i,n)=(i+1,n)+climbStairs(i+2,n),时间复杂度O(2^n),空间复杂度O(n)。
public class Solution { public int climbStairs(int n) { return climb_Stairs(0, n); } public int climb_Stairs(int i, int n) { if (i > n) { return 0; } if (i == n) { return 1; } return climb_Stairs(i + 1, n) + climb_Stairs(i + 2, n); } }
② 记录每次爬阶梯的方式。时间复杂度O(n),空间复杂度O(n)。0 ms。
public class Solution { public int climbStairs(int n) { int memo[] = new int[n + 1]; return climb_Stairs(0, n, memo); } public int climb_Stairs(int i, int n, int memo[]) { if (i > n) { return 0; } if (i == n) { return 1; } if (memo[i] > 0) { return memo[i]; } memo[i] = climb_Stairs(i + 1, n, memo) + climb_Stairs(i + 2, n, memo); return memo[i]; } }
③ 经典DP问题:
假设梯子有n层,那么如何爬到第n层呢,因为每次只能爬1或2步,那么爬到第n层的方法要么是从第n-1层一步上来的,要不就是从n-2层2步上来的,所以递推公式非常容易的就得出了:
dp[n] = dp[n-1] + dp[n-2]
如果梯子有1层或者2层,dp[1] = 1, dp[2] = 2,如果梯子有0层,自然dp[0] = 0 。时间复杂度O(n),空间复杂度O(n)。0ms。
public class Solution {
public int climbStairs(int n) {
if (n == 1) { //如果不加,会导致数组下标越界,dp[2] = 2;
return 1;
}
int[] dp = new int[n + 1];
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
}
④ 斐波拉契数列,由dp[i]=dp[i−1]+dp[i−2]我们可以得到第n层的值是一个斐波拉契数:Fib(n)=Fib(n−1)+Fib(n−2),其中Fib(1)=1 , Fib(2)=2。时间复杂度O(n),空间复杂度O(1)。
public class Solution {
public int climbStairs(int n) {
if (n == 1) {
return 1;
}
int first = 1;
int second = 2;
for (int i = 3; i <= n; i++) {
int third = first + second;
first = second;
second = third;
}
return second;
}
}