Leetcode 70. Climbing Stairs
2016-10-12 21:03
239 查看
题目链接:https://leetcode.com/problems/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?
Subscribe to see which companies asked this question
思路:动态规划,找递推公式,爬到第n级楼梯总的方式:f(n),要么从n-1级爬上来的,要么就是n-2级爬上来的,递推公式:f(n)=f(n-1)+f(n-2)
两种方法,循环和递归,递归超时(功能正确)
代码1:循环
代码2:递归
题目描述:
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?
Subscribe to see which companies asked this question
思路:动态规划,找递推公式,爬到第n级楼梯总的方式:f(n),要么从n-1级爬上来的,要么就是n-2级爬上来的,递推公式:f(n)=f(n-1)+f(n-2)
两种方法,循环和递归,递归超时(功能正确)
代码1:循环
class Solution { public: int climbStairs(int n) { if(n==1||n==2) return n; int fn_1=2; int fn_2=1; int tmp; for(int i=3;i<=n;i++) { tmp=fn_1+fn_2; fn_2=fn_1; fn_1=tmp; } return tmp; } };
代码2:递归
class Solution { public: int climbStairs(int n) { return climb(n); } int climb(int n) { int re; if(n==1||n==2) return n; re=climb(n-1)+climb(n-2); return re; } };
相关文章推荐
- leetcode(20).70. Climbing Stairs
- leetcode-Java-70. Climbing Stairs
- LeetCode:70. Climbing Stairs
- [LeetCode] 70. Climbing Stairs
- 70.[Leetcode]Climbing Stairs
- <LeetCode OJ> 70. Climbing Stairs
- LeetCode - 70. Climbing Stairs
- LeetCode 70. Climbing Stairs
- Leetcode:70. Climbing Stairs
- [LeetCode]70. Climbing Stairs
- LeetCode 70. Climbing Stairs
- [leetcode]70. Climbing Stairs
- LeetCode-70. Climbing Stairs
- LeetCode 70. Climbing Stairs
- LeetCode-70. Climbing Stairs
- LeetCode -- 70. Climbing Stairs
- LeetCode之7 Climbing Stairs
- leetcode70~Climbing Stairs
- 算法课第10周第1题——70. Climbing Stairs
- LeetCode: Climbing Stairs