首页 > 代码库 > LeetCode Jump Game

LeetCode 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,1,4], return true.

A = [3,2,1,0,4], return false.

 

一开始使用递归,结果超时了。以下是网上的解法

用贪心策略,刚开始step = A[0],到下一步step--, 并且取step = max(step, A[1]),这样step一直是保持最大的能移动步数,局部最优也是全局最优。

 1 public class Solution { 2     public boolean canJump(int[] A){ 3         if (A.length<=1)return true; 4         int step=A[0]; 5         for (int i = 0; i < A.length; i++) { 6             if (step>0){ 7                 step--; 8                 step=Math.max(step,A[i]); 9                 10             }else return false;11         }12         return true;13     }14 15 }

 

LeetCode Jump Game