【LeetCode】Climbing Stairs
2014-05-22 21:05
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?
解答
方法一:可用递归思想, 但太慢了,时间复杂度:O(2^lgn),当n逐渐变大时,时间呈指数增长
int climbStairsRecur(int n){
if(n==1) return 1;
if(n==2) return 2;
return climbStairsRecur(n-1)+climbStairsRecur(n-2);
}
方法二:使用动态规划法填表,时间复杂度:O(n)
public class Solution {
public static int climbStairs(int n) {
int[] data=new int[n+1];
data[0]=0;
data[1]=1;
if(n>=2){
data[2]=2;
}
for(int i=3;i<=n;i++){
data[i]=data[i-1]+data[i-2];
}
return data
;
}
}
直接用变量存储
int climbStairs(int n){
if(n<4)
return n;
int a=2,b=3,c=5;
for(int i=5;i<=n;i++){
a=c; //此处a只是作为变量
c=b+c;
b=a;
}
return c;
}
---EOF---
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?
解答
方法一:可用递归思想, 但太慢了,时间复杂度:O(2^lgn),当n逐渐变大时,时间呈指数增长
int climbStairsRecur(int n){
if(n==1) return 1;
if(n==2) return 2;
return climbStairsRecur(n-1)+climbStairsRecur(n-2);
}
方法二:使用动态规划法填表,时间复杂度:O(n)
public class Solution {
public static int climbStairs(int n) {
int[] data=new int[n+1];
data[0]=0;
data[1]=1;
if(n>=2){
data[2]=2;
}
for(int i=3;i<=n;i++){
data[i]=data[i-1]+data[i-2];
}
return data
;
}
}
直接用变量存储
int climbStairs(int n){
if(n<4)
return n;
int a=2,b=3,c=5;
for(int i=5;i<=n;i++){
a=c; //此处a只是作为变量
c=b+c;
b=a;
}
return c;
}
---EOF---
相关文章推荐
- leetcode做题总结,动态规划I(Triangle,Unique PathsI/II,Minimum Path Sum,Climbing Stairs,Jump Game,Word Break)
- 【leetcode】Climbing Stairs
- 52_leetcode_Climbing Stairs
- 【LeetCode】Climbing Stairs
- leetcode - Climbing Stairs
- leetcode 之 Climbing Stairs
- LeetCode【70】Climbing Stairs
- Leetcode: Climbing Stairs
- Leetcode NO.70 Climbing Stairs
- Leetcode_num13_Climbing Stairs
- LeetCode70——Climbing Stairs
- 【Leetcode】【python】Climbing Stairs
- LeetCode-Climbing Stairs
- LeetCode(70) Climbing Stairs
- LeetCode:Climbing Stairs
- leetcode -- Climbing Stairs
- LeetCode:Plus One, Add Binary, Sqrt(x), Climbing Stairs
- Leetcode--Climbing Stairs
- LeetCode - 70. Climbing Stairs
- [LeetCode-70] Climbing Stairs