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.

    public int climbStairs(int n) {
        if (n == 1)
            return 1;
        if (n == 2)
            return 2;
        int start1 = 1;
        int start2 = 2;
        int count = 0;
        for (int i = 3; i <= n; i++) {
            count = start1 + start2;
            start1 = start2;
            start2 = count;
        }
        return count;
    }
    private HashMap<Integer, Integer> mCache = new HashMap<>();

    public int climbStairs(int n) {
        if (mCache.containsKey(n))
            return mCache.get(n);
        if (n > 2) {
            int c = climbStairs(n - 1) + climbStairs(n - 2);
            mCache.put(n, c);
            return c;
        }
        if (n == 2)
            return 2;
        else if (n == 1)
            return 1;
        return 0;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容