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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_32547403/article/details/79969925

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

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

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试