This topic is a special jumping step problem, given an array, each array contains the number of steps that can be skipped in that position, and the minimum number of steps required to jump to the last position is calculated. I see this topic when the first impression of the brain is recursive, recursive solution is definitely possible, so I wrote the following code (the result is a timeout!). )
Solution One, recursive lookup, time efficiency is too low ... No, the contents of the class solution {Public:int jump (vector<int>& nums) {/* array represent the maximum number of steps that can be skipped for the position, finding the minimum number of steps required to jump to the last position */int len = Nums.size ();//vector<int> spos;int first = Nums[0];int mintimes = 0;for (int i = 1; I <= first; ++i) {//int length = Findallsolv (Nums, Spos, i); int times = Findallsolv (nums, I); if (i = = 1) {mintimes = times;} Else{if (Mintimes > times) {mintimes = Times;}}} return mintimes;} int Findallsolv (vector<int>& nums, int begin) {int times = 0;IF (Begin >= Nums.size ()) {return 0;} for (int i = 1; I <= nums[begin]; ++i) {int time = 1 + findallsolv (nums, begin + i); if (i = = 1) {times = time;} Else{if (Times > Time) {times = Time;}}} return times;}};
I found the problem! Recursive solution is included in the case of one step at a time, such a jump is certainly not the optimal solution, so when I reflect on the recursive approach I think of a better method, belongs to the greedy algorithm.
This method is really feasible, but the implementation of the time to remember the cross-border processing, a little attention may be wrong, the following is my code:
Class Solution {Public:int jump (vector<int>& nums) {/* This type of problem is still using the greedy algorithm */int pos = 0;int length = nums.size (); int ind ex = 0;if (length = = 0) {return 0;} while (Index < length-1) {int next = 0;int begin = Index;int Onejump = 0;for (int i = 1; I <= Nums[index]; ++i) {if (n Ums[index] >= length-1 | | Index + i >= length | | Index + Nums[index + i] >= length) {//[1,3,2] //[] //[2,3,1] //9, 6, 6, 2, 3, 1, 0, 9, 2, 7if (index + Nums[index] < length-1) {++pos;} Next = Length;break;} if (i + nums[index+i] > onejump) {next = I;onejump = i + Nums[index + i];}} ++pos;index + = Next;} return POS;}};
The results are as follows:
Written question 58. Leetcode OJ (45)