-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJumpGame.java
More file actions
103 lines (85 loc) · 2.9 KB
/
JumpGame.java
File metadata and controls
103 lines (85 loc) · 2.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// 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.
// See: https://leetcode.com/problems/jump-game/
// See: https://leetcode.com/explore/featured/card/30-day-leetcoding-challenge/531/week-4/3310/
package leetcode.dynamic_programming;
public class JumpGame {
/**
* Recursion with memorization (for the initial solution)
* TODO: There is a fast greedy solution - find it.
*/
private int[] memo;
public boolean canJump_(int[] nums) {
memo = new int[nums.length];
return dfs(nums, 0);
}
private boolean dfs(int[] nums, int pos) {
if (nums[pos] + pos >= nums.length - 1)
return true;
if (memo[pos] != 0)
return memo[pos] == 1 ? true : false;
boolean res = false;
for (int i = pos + 1; i <= nums[pos] + pos; i++) {
if (memo[i] != 0)
res = res || memo[pos] == 1 ? true : false;
else
res = res || dfs(nums, i);
}
memo[pos] = res ? 1 : -1;
return res;
}
/**
* Initial solution - not accepted (TLE)
*/
public boolean canJump_var1(int[] nums) {
return dfs1(nums, 0);
}
private boolean dfs1(int[] nums, int pos) {
if (nums[pos] + pos >= nums.length - 1)
return true;
boolean res = false;
for (int i = pos + 1; i <= nums[pos] + pos; i++)
res = res || dfs1(nums, i);
return res;
}
/**
* Recursion with memorization.
*/
public boolean canJump____(int[] nums) {
return helper(nums, nums.length - 1, new int[nums.length]);
}
private boolean helper(int[] nums, int end, int[] memo) {
if (nums[0] >= end)
return true;
for (int i = 1; i < end; i++) {
if (nums[i] + i >= end) {
if (memo[i] == 0)
memo[i] = helper(nums, i, memo) ? 1 : -1;
return memo[i] == 1 ? true : false;
}
}
return false;
}
/**
* Another recursive solution.
*/
public boolean canJump(int[] nums) {
return lab(nums, nums.length - 1);
}
private boolean lab(int[] nums, int end) {
if (nums[0] >= end)
return true;
for (int i = 1; i < end; i++) {
if (nums[i] + i >= end)
return lab(nums, i);
}
return false;
}
public static void main(String[] args) {
JumpGame sln = new JumpGame();
System.out.println(sln.canJump(new int[] { 2, 3, 1, 1, 4 }));
System.out.println(sln.canJump(new int[] { 3, 2, 1, 0, 4 }));
System.out.println(sln.canJump(new int[] { 2, 5, 0, 0 }));
}
}