【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.


 

题解:注意题目中A[i]代表的是从i能够跳出的最大步数,而不是从i只能跳出A[i]步。

用一个boolean型的数组记录某个位置能够到达。在位置i时,遍历所有的位置j(j<i),如果能够到达j而且能够从j跳到i,那么最终就可以到达i。

代码如下:

 

 1 public class Solution {

 2     public boolean canJump(int[] A) {

 3         if(A == null || A.length == 0)

 4             return true;

 5         

 6         boolean[] reach = new boolean[A.length];

 7         reach[0] = true;

 8         

 9         for(int i = 1;i < A.length;i++){

10             for(int j = 0;j < i;j++){

11                 if(reach[j] && j+A[j]>=i){ 

12                     reach[i] = true;

13                     break;

14                 }

15             }

16         }

17         

18         return reach[A.length-1];

19     }

20 }

你可能感兴趣的:(LeetCode)