美文网首页
Climbing Stairs

Climbing Stairs

作者: Jarhot | 来源:发表于2017-06-28 19:47 被阅读0次

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

    相关文章

      网友评论

          本文标题:Climbing Stairs

          本文链接:https://www.haomeiwen.com/subject/zjqpcxtx.html