标签:
爬楼梯的递归版本(在leetcode上超时,在本地测试通过):
class Solution {
public:
int climbStairs(int n) {
if(n == 1)
return 1;
if(n == 2)
return 2;
return climbStairs(n - 1) + climbStairs(n - 2);
}
};
爬楼梯的迭代版本:
class Solution {
public:
int climbStairs(int n) {
if(n == 1)
return 1;
if(n == 2)
return 2;
int forward,backward,tmp;
forward = 1;
backward = 2;
for(int i = 0; i < n -2; i++ ) {
tmp = forward + backward;
forward = backward;
backward = tmp;
}
return backward;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/guanzhongshan/article/details/46721809