70. Climbing Stairs
- Total Accepted: 143040
- Total Submissions: 372276
- Difficulty: Easy
- Contributors: Admin
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?
有三种解法:
1.递归,最简单,也容易懂,但是不符合本题要求,超时了。简单易懂
public class Solution {
public int climbStairs(int n) {
if(n<3)return n;
return climbStairs(n-1)+climbStairs(n-2);
}
}
2动态规划dynamic programming
public class Solution {
public int climbStairs(int n) {
//2016-12-1recode first、
//DP
//当前的情况总数是距离当1级的总数(再上一级)和距离当前2级的总数(一步再上两级(分开两步上的情况已经在1中了))的总和;
if(n<3)return n;
int[] res = new int[n+1];
res[1] = 1;
res[2] = 2;
for(int i = 3;i<=n;i++){
res[i] = res[i-1]+res[i-2];
}
return res[n];
}
}
3最简单的,空间复杂度O(1)
public class Solution {
public int climbStairs(int n) {
//2016-12-1recode first、
//简洁式
if(n<3)return n;
int res = 0;
int firstTwo = 1;//第一步迈了两步,记住这两步是捆在一起的。然后还有1中情况
int firstOne = 2;//第一步迈了一步。还有两种情况
for(int i=3;i<=n;i++){
res = firstTwo+firstOne;
firstTwo = firstOne;//再加一级,开始迈两步的就还有两级,和刚才迈一步的情况一样。
firstOne = res; //再加一家,开始迈一步的就还有三级,和刚才算出来的结果一样。
//当前的结果依赖之前算出来的结果,
}
return res;
// there firstTwo and firstOnde can replace by gapOne and gapTwo .
//也就是说离三步的距离还有一步,有一种情况,有两步,有一种情况
//n个台阶的值是固定的.1级就是1,2级就是2,四级就是5
//就是一级一级算上来的从1到n算4用到3,算5用到4
}
}