问题:
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?
思路: 设c数组为记录1...n step的distinct ways, 分析当step = n, 可能有两种情况,第一种是最后走一步,可能的走法是c[n-1], 第二种是最后走两步,可能的走法是c[n-2]. 解法类似于斐波那契队列, c[n] = c[n-1] + c[n-2], 具有最优子结构的性质和重复子问题的性质。
class Solution {
public:
int climbStairs(int n) {
// 斐波那契数列,使用一维动态规划
if(n == 1 || n == 2)
return n;
int c[3] = {1, 2, 1};
for(int i = 2; i < n; i++)
{
c[2] = c[0] + c[1];
c[0] = c[1];
c[1] = c[2];
}
return c[2];
}
};