描述:
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?
动态规划
初始状态为
dp[0] = 1, dp [1] = 1
动态规划等式
dp[n] = dp[n-1] + dp[n-2]
不难得到代码
public class Solution {
public int climbStairs(int n) {
if(n < 2) return 1;
int [] dp = new int[3];
dp[0] = 1;
dp[1] = 1;
for(int i = 2; i <= n; i++) {
dp[i % 3] = dp[(i - 1) % 3] + dp[(i - 2) % 3];
}
return dp[n % 3];
}
}
其中,对3取模是对空间进行优化,如果去掉的话可以提高运算速度,时间还是空间的抉择看人了
矩阵求解
可参考XDOJ之feibonaqi的文章,时间复杂度可由动态规划的 O(n) 下降到 O(logn)
队列求解
另外可用队列求解。代码如下:
public class Solution {
public int climbStairs(int n) {
if (n <= 1) {
return 1;
}
int last = 1, lastlast = 1;
int now = 0;
for (int i = 2; i <= n; i++) {
now = last + lastlast;
lastlast = last;
last = now;
}
return now;
}
}