Greedy from back to front is not monotonic, so the time complexity is 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;
}
};
From front to back greedy, we assume that f[i] represents the minimum number of steps to jump to position i, then for i<j, there must be f[j]>f[i], which proves to be more obvious, and can jump to j, It must be able to jump to i. Therefore, it can be recursed section by section.
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];
}
};