代码改变世界

70_Climbing Stairs

2016-03-21 20:28  FTD_W  阅读(175)  评论(0编辑  收藏  举报

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?

一共N阶楼梯,一次只上1阶或2阶,求一共多少种上楼梯的方法。

动态规划问题

f(n)为总数为n个楼梯的走法总数

f(n) = f(n - 1)           (走一步)

   + f(n - 2)          (走两步)

 

int climbStairs(int n) {
    int count[n + 1];
    count[0] = 0;
    count[1] = 1;
    count[2] = 2;
    if(n == 0 || n == 1)
    {
        return 1;
    }
    if(n == 2)
    {
        return 2;
    }
    for(int i = 3; i < n + 1; i++)
    {
        count[i] = count[i - 1] + count[i - 2];
    }
    return count[n];
}