this question is a complicated jumping step problem, mainly is the test can jump to the end, it is not like those before the steps of the problem, the previous will not consider whether can jump out of the problem. So the previous program used here is likely to lead to a dead loop, my main idea is "greedy algorithm + screening conditions" to solve problems.
1. Greedy algorithm is mainly used to reduce the number of hops
We can jump from the current position (cur) to the number of steps (N), and the current position jumps in the range [Cur~cur+n] Each step can jump the maximum distance; combine the two to determine where the next jump should be. Some people will say that this will not miss the problem of the positive solution? The following criteria can be used to illustrate the problem.
2. The screening condition is used to filter out "dead steps (the distance that the stair can jump to 0)"
Filter condition is to filter off a position to jump distance of 0 steps, if the next step can jump the distance of 0 then the step cannot jump, we should filter off a jump in the steps of all can jump the distance of 0 steps; Because we always filter out the steps can not jump, so not only do not miss the positive solution, can help us find the positive solution, if this can not be understood, it is recommended to take a good look at the code and self-test on the paper on the feasibility of the method.
The above two methods are in fact at the same time, so in the writing code need to pay attention to these problems, the code is as follows, where the key points give a comment, hope to help you understand the idea.
Class Solution {Public:int canjump (vector<int>& nums) {/* This type of problem still uses the greedy algorithm */int length = Nums.size (); int index = 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 (Nums[index] >= length-1 | | index + i >= length-1 | | Index + NUMS[INDEX + i] >= length-1) {return true;} if (i + Nums[index + i] > onejump && nums[index+i]!= 0) {next = I;onejump = i + Nums[index + i];}} if (next = = 0) {return false;} Index + = Next;} Return (index >= length-1);};
The results are as follows:
Written question 68. Leetcode OJ (55)