Jump Game

来源:互联网 发布:自学java不学c语言 编辑:程序博客网 时间:2024/05/17 01:16

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.



Solution:

1. one-dimensional dynamic programming. Define an array dp[i] to store the maximum number of steps that is left.


2. Formula: dp[i] = Max(dp[i - 1], A[i - 1]) - 1;


public class Solution {    public boolean canJump(int[] nums) {        if (nums == null || nums.length == 0)            return false;                           int[] dp = new int[nums.length];        dp[0] = 0;        for (int i = 1; i < nums.length; i++) {            dp[i] = Math.max(dp[i - 1], nums[i - 1]) - 1;                        if (dp[i] < 0)                return false;        }                return dp[nums.length - 1] >= 0;    }}


0 0
原创粉丝点击