您的位置:首页 > 大数据 > 人工智能

【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---
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: