题目要求如下:
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?
本题也是第二次做,不过这次更加了解dynamic programming的编程思想。。。设定一个数组 method[n+1]存储到每一步的方法数目
method[0]是0种方法。
method[1]只有一种方法
method[2]有两种:1+1, 2
method[3]有3种方法,即从method[1]走2,以及从method[2]走一步
所以method[n] = method[n-1] + method[n-2]
详细代码如下所示:
class Solution {
public:
int climbStairs(int n) {
int *method = new int [n+1];
method[0] = 0;
method[1] = 1;
method[2] = 2;
for (int i = 3; i <= n; ++i)
method[i] = method[i-1] + method[i-2];
return method[n];
}
};