Leetcode Climbing Stairs
2015-05-16 19:03
267 查看
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?
爬楼梯问题,每一次可以爬1阶或者2阶,问爬上N阶的选择法,爬上1阶的选择1种,爬上2阶的选择有2种,
爬上N阶的选择有f(N) = f(N-1)+f(N-2).....
当使用递归算法的时候会超时!!!!!!
改进方法后.......
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
爬楼梯问题,每一次可以爬1阶或者2阶,问爬上N阶的选择法,爬上1阶的选择1种,爬上2阶的选择有2种,
爬上N阶的选择有f(N) = f(N-1)+f(N-2).....
当使用递归算法的时候会超时!!!!!!
class Solution { public: int climbStairs(int n) { if(n==1) return 1; if(n==2) return 2; return climbStairs(n-1)+climbStairs(n-2); } };
Submission Result: Time Limit Exceeded
改进方法后.......class Solution { public: int climbStairs(int n) { int result,s1=1,s2=2; if(n==1) return s1; if(n==2) return s2; for(int i=3;i<=n;i++) { result = s1 + s2; s1 = s2; s2 = result; } return result; } };
Submission Result: Accepted
相关文章推荐
- LeetCode:70. Climbing Stairs
- Climbing Stairs-LeetCode
- leetCode: Climbing Stairs
- LeetCode:Plus One, Add Binary, Sqrt(x), Climbing Stairs
- leetcode 70: Climbing Stairs
- 【LeetCode with Python】 Climbing Stairs
- [LeetCode]--Climbing Stairs
- leetcode 虐我篇之(二十一)Climbing Stairs
- leetcode-70 Climbing Stairs
- LeetCode:Climbing Stairs
- [leetcode] Climbing Stairs
- LeetCode70——Climbing Stairs
- LeetCode | Climbing Stairs
- 【leetcode】【70】Climbing Stairs
- 【题解】【DP】【Leetcode】Climbing Stairs
- LeetCode: Climbing Stairs
- [Leetcode 70, easy] Climbing Stairs
- [LeetCode] Climbing Stairs
- Leetcode[72]-Climbing Stairs
- 【LeetCode】遇到一个很有趣的问题:Climbing Stairs