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.
首先是递归的算法,但是会超时
接着用一个数组存储到第i步有多少种走法,但是这样的空间复杂度为O(n);
最后,将空间复杂度降为O(1);
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; }
相关文章推荐
- 70. Climbing Stairs
- leetcode 70. Climbing Stairs
- 70. Climbing Stairs
- 70. Climbing Stairs
- LeetCode OJ-70. Climbing Stairs(爬楼梯问题)
- 70. Climbing Stairs (Easy)
- LeetCode 70. Climbing Stairs
- 70. Climbing Stairs
- LeetCode 70. Climbing Stairs
- leetcode 70. Climbing Stairs
- 70. Climbing Stairs
- Leetcode 70. Climbing Stairs
- 算法分析与设计week14--70. Climbing Stairs
- 70. Climbing Stairs(爬楼梯)
- 70. Climbing Stairs
- 【LeetCode】70. Climbing Stairs
- 70. Climbing Stairs
- LeetCode 70. Climbing Stairs(爬楼梯)
- Leetcode 70. Climbing Stairs
- 70. Climbing Stairs