劍指offer——跳臺階

baixiaofei567發表於2020-12-23

在這裡插入圖片描述
和斐波那契一模一樣,迴圈和遞迴都可以

class Solution {
public:
    vector<int> dp;
    int jumpFloor(int number) {
        //dp即可
        dp.resize(number+2);
        if(number == 1) return 1;
        if(number == 2) return 2;
        for(int i = 1 ; i <= number; i++){
            dp[i] = -1;
        }
        dp[1] = 1;
        dp[2] = 2;
        return sum(number-1) + sum(number-2);
    }
    int sum(int n){
        if(n == 1) return 1;
        if(n == 2) return 2;//遞迴邊界
        if(dp[n] != -1) return dp[n];
        else{
            dp[n] = sum(n-1) + sum(n-2);
            return dp[n];
        }
    }
};

相關文章