image.png

自底向上的动态规划

image.png

  1. class Solution {
  2. enum Index {GOOD,UNKNOWN};
  3. public boolean canJump(int[] nums) {
  4. Index[] memo = new Index[nums.length];
  5. for (int i = 0; i < memo.length; i++) {
  6. memo[i] = Index.UNKNOWN;
  7. }
  8. memo[memo.length - 1] = Index.GOOD;
  9. for (int i = nums.length - 2; i >= 0; i--) {
  10. int furthestJump = Math.min(nums[i] + i,nums.length - 1);
  11. for (int j = i + 1;j <= furthestJump;j++){
  12. if (memo[j] == Index.GOOD){
  13. memo[i] = Index.GOOD;
  14. break;
  15. }
  16. }
  17. }
  18. return memo[0] == Index.GOOD;
  19. }
  20. }

贪心

image.png

  1. public class Solution {
  2. public boolean canJump(int[] nums) {
  3. int lastPos = nums.length - 1;
  4. for (int i = nums.length - 1; i >= 0; i--) {
  5. if (i + nums[i] >= lastPos) {
  6. lastPos = i;
  7. }
  8. }
  9. return lastPos == 0;
  10. }
  11. }