LeetCode 70. Climbing Stairs
2016-05-31 21:57
399 查看
Climbing Stairs
Des
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?
分析
一开始看到这个题就蒙逼了,思路一下跑高中的排列组合去了,跑了好久,可是题明明是easy的题觉得是自己思路有偏差,不得已还是先学习别人的思路吧,没基础只能这么慢慢弄了。看别人的起码学习到了思考问题的思路。递归法:
上这个楼梯可以一下上2个或者1个,递归就是找出问题最后不能再分的那个地方,把这个规定好别的递归就行了,那么就是在n==2时有2种方法,n==1时有1种方法。但是这个存在问题就是当n大时会超时,但是如何建立递归的思想还是值得借鉴的。class Solution { public: int climbStairs(int n) { if(n==1) return 1; if(n==2) return 2; return climbStairs(n-1)+climbStairs(n-2); } };
斐波那契数列
仔细推导一下才发现,这其实是一个斐波那契数列,这个大家都懂不再细说。Code
class Solution { public: int climbStairs(int n) { int a=0; int b=1; int sum=0; for(int i=1;i<=n;i++){ sum=a+b; a=b; b=sum; } return sum; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解