贪心算法的证明过程Leetcode 45 跳跃游戏

 

从后往前贪心没有单调性,所以时间复杂度是O(n^2)

class Solution {
public:
    int jump(vector<int>& nums) {
        /* 假设存在一段路径0->P1->P2->P3->n-1是最优路径
        我们选取一个中间路径L,使得L<=P3,但L能跳到n-1
        即贪心策略是每次从终点选择最靠左的路径。
        这样的时间复杂度是O(n^2)
        */
        int n = nums.size(), last = nums.size()-1;
        int res = 0;
        while(last!=0){
            int tmp = last;
            for(int j=last-1;j>=0;j--){
                if(nums[j]+j>=last){
                    tmp = j;
                }
            }
            last = tmp;
            res++;
        }
        return res;
    }
};

从前往后贪心,我们假设f[i]表示跳到i位置的最少步数,那么对于i<j, 一定有f[j]>f[i],  证明是比较显然的,能跳到j,就一定能跳到i。 因此可以一段一段的递推。

class Solution {
public:
    int jump(vector<int>& nums) {
        int n = nums.size();
        vector<int> f(n);
        for(int i=1,j=0;i<n;i++){
            while(nums[j]+j<i) j++;
            f[i] = f[j]+1;
        }
        return f[n-1];
    }
};

 

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/113853470