爬楼梯
题目
假设你正在爬楼梯,需要n步你才能到达顶部。但每次你只能爬一步或者两步,你能有多少种不同的方法爬到楼顶部?
样例
比如n=3,1+1+1=1+2=2+1=3,共有3中不同的方法
返回 3
题解
DP问题
状态转移方程:f[i] = f[i-1] + f[i-2];,下面的解法用两个变量first和next代替了一维数组f[n],降低了空间复杂度。
public class Solution {
/**
* @param n: An integer
* @return: An integer
*/
public int climbStairs(int n) {
int result = 1;
int first = 1;
int next = 1;
while (--n > 0)
{
result = first + next;
first = next;
next = result;
}
return result;
}
}
Last Update 2016.9.6