Skip to content

Commit

Permalink
https://leetcode.com/problems/jump-game/
Browse files Browse the repository at this point in the history
  • Loading branch information
s50600822 committed Oct 29, 2023
1 parent 4f1a3cd commit 3209d58
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package hoa.can.code.gg;

import java.util.Arrays;

/**
* https://leetcode.com/problems/jump-game/
*/
public class Jumping {
final static int NO_WAY = Integer.MAX_VALUE;
public static boolean canJump(int[] nums) {
int[] memo = new int[nums.length];
Arrays.fill(memo, -1);
return (minJumps(nums, 0, nums.length - 1, memo) > -1);
}
private static int minJumps(int steps[], int begin, int dest, int[] memo) {
if (begin == dest)
return 0;
if (steps[begin] == 0)
return NO_WAY;

int minJump = NO_WAY;
for (int step = steps[begin]; step >= 1; --step) {
if (begin + step <= dest) {
minJump = Math.min(minJump, 1 + minJumps(steps, begin + step, dest, memo));
}
}
return memo[begin] = minJump;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package hoa.can.code;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static hoa.can.code.gg.Jumping.canJump;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class JumpingTest {
@Test
@DisplayName("ok")
public void yes() {
assertEquals(true, canJump(new int[]{2, 3, 1, 1, 4}));
assertEquals(true, canJump(new int[]{1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9}));
}

@Test
@DisplayName("nope")
public void no() {
assertEquals(true, canJump(new int[]{0}));
assertEquals(true, canJump(new int[]{0,1}));
}
}

0 comments on commit 3209d58

Please sign in to comment.