https://oj.leetcode.com/problems/jump-game-ii/
给一个数列,每次可以跳相应位置上的步数,问跳到最后位置至少用几步。
动态规划:
j[pos]表示从0到pos至少要跳的步数,初始化为n
j[pos] = min { j[i] + 1 ,j[pos]} if(A[i] + i >=pos) i 从0到pos
这属于一维动态规划
class Solution { public: int jump(int A[], int n) { if(n == 0) return 0; vector<int> ans; ans.resize(n); ans[0] = 0; for(int i = 1;i<n;i++) { ans[i] = n;//initialize for(int j = 0;j<i;j++) { if(A[j] + j >= i) ans[i] = min(ans[i],ans[j] + 1); } } return ans[n-1]; } };
复杂度为O(n*n)超时了。
于是看了答案,用贪心,类似宽度优先搜索的概念。
维护一个当前范围(left,right)表示从当前范围经过一步可以调到的范围(min_distance,max_distance)。
class Solution { public: int jump(int A[], int n) { if(n == 0) return 0; if(n==1) return 0; int ans_step = 0; int left = 0, right = 0; int max_distance = 0; int min_distance = n; while(1) { ans_step++; max_distance = 0; min_distance = n; int i; for(i = left; i <= right && i< n;i++) { int this_time = i + A[i]; if( this_time > max_distance) max_distance = this_time; if(max_distance >= n-1) return ans_step; } if(i == n) break; i = left; bool flag = false; while(i<=right) {
//find the first number not 0 if(A[i]!=0) { min_distance = i + 1; flag = true; break; } i++; } if(flag == false) break; right = max_distance; left = min_distance; } return n; } };