剑指 Offer 10- II. 青蛙跳台阶问题

https://leetcode-cn.com/problems/qing-wa-tiao-tai-jie-wen-ti-lcof/

  • 动态规划
class Solution {
    public int numWays(int n) {
        if(n==0)return 1;
        if(n==1)return 1;
        if(n==2)return 2;
        int[] arr = new int[n+1];
        arr[0]=1;
        arr[1]=1;
        arr[2]=2;
        for(int i=3;i<=n;i++){
            arr[i]=arr[i-1]+arr[i-2];
            arr[i] %= 1000000007;
        }
        return arr[n];
    }
}
//O(1)空间法
class Solution {
    public int numWays(int n) {
        int a = 1, b = 1, sum;
        for(int i = 0; i < n; i++){
            sum = (a + b) % 1000000007;
            a = b;
            b = sum;
        }
        return a;
    }
}

你可能感兴趣的:(剑指 Offer 10- II. 青蛙跳台阶问题)