Climbing Stairs II (使用滚动数组进行优化)

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?

java

public class Solution {
    /**
     * @param n: An integer
     * @return: An integer
     */
    public int climbStairs(int n) {
        // write your code here
        if (n <= 2) {
            return n;
        }
        int[] f = new int[3];
        f[0] = 1;
        f[1] = 1;
        for (int i = 2; i < n + 1; i++) {
            f[i % 3] = f[(i - 1) % 3] + f[(i - 2) % 3];
        }
        return f[n % 3];
    }
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_32547403/article/details/79969925
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭