【LeetCode】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?

解答

方法一:可用递归思想, 但太慢了,时间复杂度: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[n];
    }
}

直接用变量存储

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---

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值