Jump game
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
For example:
A = [2, 3, 1, 4], return true.
A = [3, 2, 1, 0, 4], return false.
Solutions:
1. dp1
At each vertex I, we scan all previous vertices. If a vertex J itself is reachable and is reachable with the current vertex, it indicates that vertex I is reachable.
Return Value: The last value of the DP array.
View code
2. dp2
Optimization Point 1: since a certain point is reachable, it is sure that all the preceding points are reachable. This is easy to understand. Because you must pass through the previous point when you arrive at the I point, this one knows in turn that all the points above can be reached.
Therefore, we do not need an array to record the results, as long as all can be reached before the default I point.
Optimization Point 2: if a certain point cannot be reached, false is returned directly. You do not need to calculate it later.
Returned value: If all scans are complete, false is returned. True is returned.
View code
3. Recursion
The idea is to calculate whether J points are reachable from the first scan to the Point J that is reachable from the first scan to the current point. Use recursive calculation J
Point accessibility.
In fact, greedy thinking is still used here. When considering whether the current vertex is reachable, we consider whether the farthest point from the current vertex is reachable. In fact, this also makes sense.
Assume that the J point can reach the I point, then the following points can be ignored.
(1) Because J + 1 cannot be reached if J is not reachable. If I cannot be reached, the following points are not counted.
(2) If J points can be reached and J points can reach I, there is no need to calculate them later. Because the conclusion has come out.
(3) If J points are reachable but J points are inaccessible to I, the calculation continues.
View code
4. GitHub code
Canjump. Java
References:
Thank you for your inspiration at http://blog.csdn.net/fightforyourdream/article/details/14237949.
Leetcode: Jump game total solution report