LintCode 116. Jump Game 原创Java参考解答

LintCode 116. Jump Game 原创Java参考解答

问题描述

http://www.lintcode.com/en/problem/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.

Notice

This problem have two method which is Greedy and Dynamic Programming.

The time complexity of Greedy method is O(n).

The time complexity of Dynamic Programming method is O(n^2).

We manually set the small data set to allow you pass the test in both ways. This is just to let you learn how to use this problem in dynamic programming ways. If you finish it in dynamic programming ways, you can try greedy method to make it accept again.

Example

A = [2,3,1,1,4], return true.

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

解题思路

题目求是否能跳到数组最后一个位置。

求是否的动态规划题。

  1. 状态方程,canJump[x] 表示是否能跳到数组第i位置。除了canJump[0] = true, 其他初始值设为false。
  2. 二重循环,i < A.length、j < i ,依依测试从第j位置能否跳到第i位置。
  3. 如果 A[j] + j > i (即j能够跳到i位置) 且 canJump[j] == true(即第 j 位置已经测试可以跳到),那么canJump[i] 也就为true。
  4. 看最后一步canJump[A.length – 1]是否能跳到。

参考代码

public class Solution { 
    /** 
     * @param A: A list of integers 
     * @return: The boolean answer 
     */ 
    public boolean canJump(int[] A) { 
        boolean[] canJump = new boolean[A.length]; 
         
        canJump[0] = true; 
         
        for (int i = 0; i < A.length; i++) { 
            for (int j = 0; j < i; j++) { 
                if (canJump[j] && A[j] + j >= i) { 
                    canJump[i] = true; 
                    break; 
                } 
            }     
        } 
         
        return canJump[A.length - 1]; 
    } 
} 

相关题目

LintCode All in One 原创题目讲解汇总

LintCode 117. Jump Game II 原创Java参考解答

发表回复

您的电子邮箱地址不会被公开。