leetCode练习(70)

题目:Climbing Stairs

难度:easy

问题描述:

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?

解题思路:爬梯子,每次爬1格或者2格,求有多少种爬法。解题关键:从终点开始算,第I级梯子的爬法=(I-1)级的爬法+(I-2)级的爬法。

使用动态规划即可。第一种方法设置了数组ways[I]来记录每级梯子的爬法。第二种进行了优化,只记录要算的梯子方法数的前两级梯子的爬法。

方法一代码如下:

public static int climbStairs(int n) {
        int[] ways=new int[n+1];
        if(n==1||n==0){
        	return 1;
        }
        ways[n--]=1;
        ways[n--]=1;
        while(n>=0){
        	ways[n]=ways[n+1]+ways[n+2];    	
        	n--;
        }
        return ways[0];
    }

方法二代码如下:

public static int climbStairs2(int n) {
        int qian,hou,temp;
        if(n==1||n==0){
        	return 1;
        }
        qian=1;//上一级
        hou=1;   
        n=n-2;
        while(n>=0){
        	temp=qian+hou;
        	qian=hou;
        	hou=temp;     	
        	n--;
        }
        return hou;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值