55. Jump Game

来源:互联网 发布:唐狮质量怎么样 知乎 编辑:程序博客网 时间:2024/06/05 03:38
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,1,4], return true.
A = [3,2,1,0,4], return false.

This is a dynamic programming[1] question. Usually, solving and fully understanding a dynamic programming problem is a 4 step process:
  1. Start with the recursive backtracking solution
  2. Optimize by using a memoization table (top-down[3] dynamic programming)
  3. Remove the need for recursion (bottom-up dynamic programming)
  4. Apply final tricks to reduce the time / memory complexity
All solutions presented below produce the correct result, but they differ in run time and memory requirements.

第一次就直接写出了3 还不错 这里的贪心算法不是很难 可以看看

public boolean canJump(int[] nums) {        int lastPos = nums.length - 1;        for (int i = nums.length - 1; i >= 0; i--) {            if (i + nums[i] >= lastPos) {                lastPos = i;            }        }        return lastPos == 0;    }

每次尝试最右的点 跳最大步数 看是否能达到 lastPos
一开始纠结会不会忽略情况 比如
5 3 2 1 4
1可以到达4 2也可以 1会被作为lastPos 那后面就是找能到达1的点 会不会忽略到达2的情况 实际是不会的 
2可以到达4 那就可以到达1 所以2就会被选作下一次的lastPos
相当于2->4被拆成了 2->1->4 大步被拆成小步 最终效果是一样的


原创粉丝点击