本文主要是介绍[leetcode刷题系列]Jump Game II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
利用stack优化, 然后每次dp的时候二分查找就好了nlgn的解法,想&写出来只需要6
const int MAXN = 1e6 + 10;
int stk_top = 0;
int dp[MAXN], stk[MAXN];
class Solution {
public:int jump(int A[], int n) {// Start typing your C/C++ solution below// DO NOT write int main() functiondp[n - 1] = 0;stk_top = 0;stk[stk_top ++ ] = n - 1;for(int i = n - 2; i >= 0; -- i){int reach = i + A[i];int low = 0, high = stk_top - 1, mid;while(low <= high)if(stk[mid = low + high >> 1] <= reach)high = mid - 1;else low = mid + 1;if(low >= stk_top){dp[i] = -1;}else{dp[i] = dp[stk[low]] + 1;while(stk_top > 0)if(dp[stk[stk_top - 1]] >= dp[i]) -- stk_top; else break;stk[stk_top ++ ] = i;}}return dp[0];}
};
分钟- -
这篇关于[leetcode刷题系列]Jump Game II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!