Jump Game

Dynamic Programming, Greedy

Medium

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.

Example 1:

Input:
 [2,3,1,1,4]

Output:
 true

Explanation:
 Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input:
 [3,2,1,0,4]

Output:
 false

Explanation:
 You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.

Analysis

转化为子问题

n = nums.length。问题是否能到达n - 1 ,可以转化为:

是否n - 2能否到达,以及从 n - 2是否能到达n - 1

或者n - 3是否能到达,并且从n - 2是否能到达n - 1

或者n - 4是否能到达,并且从n - 4是否能到达n - 1

....

或者0是否能到达,并且从0是否能到达n - 1

因此可以设定动态规划状态dp[i]: 从开始出发能否到达index = i

初始值dp[0] = true, 第一个初始位置一定可以到达

dp[i] = false代表dp[i]不确定能否到达,需要在后续bottom-up过程中得到答案

那么转移方程为:

if (dp[j] && j + nums[j] >= i) {
    dp[i] = true;
    break;
}

最终结果则是:

dp[n-1]

参考:https://leetcode.com/articles/jump-game/

其中还有top-down的记忆化搜索,bottom-up的动态规划,贪心greedy等方法。

Solution

DP - Bottom Up

Time O(n^2), Space O(n)

class Solution {
    public boolean canJump(int[] nums) {
        if (nums == null) return false;
        int n = nums.length;
        boolean dp[] = new boolean[n];

        dp[0] = true; // init

        for (int i = 1; i < n; i++) {
            dp[i] = false;
            for (int j = 0; j < i; j++) {
                if (dp[j] && j + nums[j] >= i) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[n - 1];
    }
}

Greedy

Complexity Analysis

  • Time complexity : O(n). We are doing a single pass through thenumsarray, hencennsteps, wherennis the length of arraynums.

  • Space complexity : O(1). We are not using any extra memory.

public class Solution {
    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;
    }
}

Reference

https://leetcode.com/articles/jump-game/

Last updated