LeetCode-70. Climbing Stairs
2018-01-04 19:08
387 查看
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.
Output: 2
Explanation: There are two ways to climb to the top.
1 step + 1 step
2 steps
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1 step + 1 step + 1 step
1 step + 2 steps
2 steps + 1 step
我们用一个长度为n+1的一维数组来保存爬到n层的共有多少种方法。由给出的例子可知爬1层只有1种方法,爬2层有2种方法,爬3层就是在1层再一次性爬2层的方法数与在2层再一次性爬1层的方法数之和,由此可以推出爬n层就是爬n-2层的方法数与爬n-1层的方法数之和,从而得到递推式dp
=dp[n-2]+dp[n-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.
例子
Input: 2Output: 2
Explanation: There are two ways to climb to the top.
1 step + 1 step
2 steps
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1 step + 1 step + 1 step
1 step + 2 steps
2 steps + 1 step
分析
这题的解法有很多,因为我是在集中做DP的题目,所以这里只给出一种动态规划思想的解法。我们用一个长度为n+1的一维数组来保存爬到n层的共有多少种方法。由给出的例子可知爬1层只有1种方法,爬2层有2种方法,爬3层就是在1层再一次性爬2层的方法数与在2层再一次性爬1层的方法数之和,由此可以推出爬n层就是爬n-2层的方法数与爬n-1层的方法数之和,从而得到递推式dp
=dp[n-2]+dp[n-1]。
实现
class Solution { public int climbStairs(int n) { if(n==1) return 1; int[] dp=new int[n+1]; dp[1]=1; dp[2]=2; for(int i=3;i<=n;++i) { dp[i]=dp[i-1]+dp[i-2]; } return dp ; } }
相关文章推荐
- LeetCode:70. Climbing Stairs
- leetcode-Java-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(20).70. Climbing Stairs
- 70.[Leetcode]Climbing Stairs
- LeetCode 70. Climbing Stairs
- <LeetCode OJ> 70. Climbing Stairs
- [LeetCode] Climbing stairs 爬楼梯问题
- LeetCode---(70)Climbing Stairs
- Leetcode_num13_Climbing Stairs
- 开始刷leetcode day18:Climbing Stairs