Leetcode算法学习日志-70 Climbing Stairs
2017-08-13 16:16
501 查看
Leetcode 70 Climbing Stairs
题目原文
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.
题意分析
求总的走法,可以采用逆向思维,分为最后一步是走的两步还是一步。解法分析
采用逆向思维的方式,利用将最后一步除去,求解剩余的子问题,子问题的解能组成原问题的解。此题虽然不是最优化问题,但也是采用动态规划的方法。令原问题的解为W(n),则递归方程为W(n)=W(n-1)+W(n-2),采用自底向上的方法,先求出W(n-1)+W(n-2),即可得到W(n),并且此题每种规模的问题就一个,直接由小到大加起来即可,类似斐波拉切数列,所以不需要存储每一个规模的问题,只需要在用的时候放入两个零时变量中。C++代码如下:class Solution {
public:
int climbStairs(int n) {
if(n==0)
return 0;
vector<int> ways(n+2,0);
ways[0]=0;
ways[1]=1;
int i;
for(i=2;i<n+2;i++)
ways[i]=ways[i-1]+ways[i-2];
return ways[i-1];
}
};由于只有一个for循环,所以算法复杂度为O(n)。
相关文章推荐
- Leetcode算法学习日志-338 Counting Bits
- Leetcode算法学习日志-399 Evaluate Division
- Leetcode算法学习日志-54 Spiral Matrix
- Leetcode算法学习日志-735 Asteroid Collision
- Leetcode算法学习日志-86 Partition List
- Leetcode算法学习日志-121 Best Time to Buy and Sell Stock
- Leetcode算法学习日志-738 Monotone Increasing Digits
- Leetcode算法学习日志-452 Minimum Number of Arrows to Burst Balloons
- Leetcode算法学习日志-737 Sentence Similarity II
- Leetcode算法学习日志-611 Valid Triangle Number
- Leetcode算法学习日志-494 Target Sum
- Leetcode算法学习日志-563 Binary Tree Tilt
- Leetcode算法学习日志-60 Permutation Sequence
- Leetcode算法学习日志-553 Optimal Division
- Leetcode算法学习日志-576 Out of Boundary Paths
- Leetcode算法学习日志-561 Array Partition I
- Leetcode算法学习日志-241 Different Ways to Add Parentheses
- Leetcode算法学习日志-386 Lexicographical Numbers
- Leetcode算法学习日志-137 Single Number II
- Leetcode算法学习日志-752 Open the Lock