Climbing Stairs

来源:互联网 发布:复杂网络理论百度百科 编辑:程序博客网 时间:2024/06/17 03:18

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层楼梯的方法总数s(n),可以根据是否会踏上第n-1层楼梯从而分成两类方法:第一种是先上n-1层,最后再上1层,对应s(n-1)*1种方法;第二种是先上n-2层,最后直接上2层,对应s(n-2)*1种方法。故最后s(n)=s(n-1)+s(n-2)。

另外此题不能用简单的递归函数计算,因为leetcode会报超时。所以采用DP,即保存子问题计算结果的思想,避免冗余计算。

int climbStairs(int n) {int a[1000] = {0,1,2};int i = 3;if(n == 1)return a[1];if(n == 2)return a[2];else{while(i <= n){a[i] = a[i - 1] + a[i - 2];i++;}return a[n];}}


0 0