您的位置:首页 > 大数据 > 人工智能

70. Climbing Stairs dynamic programming

2017-06-19 15:20 405 查看
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?

Note: Given n will be a positive integer.

首先是递归的算法,但是会超时

int climbStairs(int n) {
if (n <= 0)return 0;
else if (n == 1)return 1;
else if (n == 2)return 2;
return climbStairs(n - 1) + climbStairs(n - 2);
}


接着用一个数组存储到第i步有多少种走法,但是这样的空间复杂度为O(n);

int climbStairs(int n) {
vector<int>my;
if (n <= 0)return 0;
else if (n == 1)return 1;
else if (n == 2)return 2;
my.push_back(0);
my.push_back(1);
my.push_back(2);
for (int i = 3; i <= n; i++){
my.push_back(my[i - 1] + my[i - 2]);
}
return my
;
}


最后,将空间复杂度降为O(1);

int climbStairs(int n) {
if (n == 0)return 0;
if (n == 1)return 1;
if (n == 2)return 2;
int pre = 1, cur = 2, next = 0;
for (int i = 3; i <= n; i++){
next = pre + cur;
pre = cur;
cur = next;
}
return cur;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: