Leetcode note--Leetcode 70climbing Stairs

70. Climbing Stairs

  • Total Accepted: 143040
  • Total Submissions: 372276
  • Difficulty: Easy
  • Contributors: Admin

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.递归,最简单,也容易懂,但是不符合本题要求,超时了。简单易懂

public class Solution {
    public int climbStairs(int n) {
        if(n<3)return n;
        return climbStairs(n-1)+climbStairs(n-2);
    }
}
2动态规划dynamic programming

public class Solution {
    public int climbStairs(int n) {
        //2016-12-1recode first、
        //DP
        //当前的情况总数是距离当1级的总数(再上一级)和距离当前2级的总数(一步再上两级(分开两步上的情况已经在1中了))的总和;
        if(n<3)return n;
        int[] res = new int[n+1];
        res[1] = 1;
        res[2] = 2;
        for(int i = 3;i<=n;i++){
            res[i] = res[i-1]+res[i-2];
        }
        return res[n];
    }
}

3最简单的,空间复杂度O(1)

public class Solution {
    public int climbStairs(int n) {
        //2016-12-1recode first、
        //简洁式
        if(n<3)return n;
        int res = 0;
        int firstTwo = 1;//第一步迈了两步,记住这两步是捆在一起的。然后还有1中情况
        int firstOne = 2;//第一步迈了一步。还有两种情况
        for(int i=3;i<=n;i++){
            res = firstTwo+firstOne;
            firstTwo = firstOne;//再加一级,开始迈两步的就还有两级,和刚才迈一步的情况一样。
            firstOne = res;     //再加一家,开始迈一步的就还有三级,和刚才算出来的结果一样。
                                //当前的结果依赖之前算出来的结果,
        }
        return res;
        // there firstTwo and firstOnde can replace by gapOne and gapTwo .
        //也就是说离三步的距离还有一步,有一种情况,有两步,有一种情况
        //n个台阶的值是固定的.1级就是1,2级就是2,四级就是5
        //就是一级一级算上来的从1到n算4用到3,算5用到4
    }
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值