Skip to content

Commit

Permalink
Update 0055-jump-game.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
a93a authored May 23, 2023
1 parent a35da60 commit 7fa5229
Showing 1 changed file with 31 additions and 1 deletion.
32 changes: 31 additions & 1 deletion kotlin/0055-jump-game.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/*
* O(n) greedy
*/
class Solution {
fun canJump(nums: IntArray): Boolean {
var goal = nums.size - 1
Expand All @@ -9,4 +12,31 @@ class Solution {
}
return goal == 0
}
}
}

/*
* O(n^2) DP + memoization
*/
class Solution {
fun canJump(nums: IntArray): Boolean {
val deadEnd = BooleanArray(nums.size)

fun canJump(i: Int): Boolean {
if (i == nums.lastIndex)
return true
if (nums[i] == 0 || deadEnd[i] == true)
return false

for (jump in 1..nums[i]) {
if (i + jump <= nums.lastIndex && canJump(i + jump)) {
return true
}
}

deadEnd[i] = true
return false
}

return canJump(0)
}
}

0 comments on commit 7fa5229

Please sign in to comment.