forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0055-jump-game.kt
42 lines (36 loc) · 888 Bytes
/
0055-jump-game.kt
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
/*
* O(n) greedy
*/
class Solution {
fun canJump(nums: IntArray): Boolean {
var goal = nums.size - 1
for (i in nums.size - 2 downTo 0) {
if (i + nums[i] >= goal) {
goal = i
}
}
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)
}
}