70. 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?

Note: Given n will be a positive integer.

一刷
题解:dynamic programming,且存在递归的表达式a[n] = a[n-1] + a[n-2]

方法一:直接用递归,但会造成超时,可能是数字太大时栈太长。并且比起用数组存起来中间结果不会更节约space。

public class Solution {
    public int climbStairs(int n) {
        if(n == 1 || n==0) return 1;
        if(n<0) return 0;
        return climbStairs(n-1) + climbStairs(n-2);
    }
}

方法二:用数组存起来中间结果。

public class Solution {
    public int climbStairs(int n) {
        int[] res = new int[n+1];
        res[0] = 1;
        res[1] = 1;
        for(int i=2; i<=n; i++){
            res[i] = res[i-1] + res[i-2];
        }
        return res[n];
    }
}

方法三,用常量存储 res[i-1], res[i-2]; 将space complexity降到O(1)

public class Solution {
    public int climbStairs(int n) {
        if(n == 1 || n==0) return 1;
        if(n<0) return 0;
        int oneStep = 1, twoStep = 2;
        if(n == 1) return oneStep;
        if(n == 2) return twoStep;
        int sum = 0;
        for(int i=3; i<=n; i++){
            sum = oneStep + twoStep;
            oneStep = twoStep;
            twoStep = sum;
        }
        return sum;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容