-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0045-jump-game-ii.kt
50 lines (44 loc) · 1.03 KB
/
0045-jump-game-ii.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
43
44
45
46
47
48
49
50
/*
* O(n) BFS
*/
class Solution {
fun jump(nums: IntArray): Int {
var left = 0
var right = 0
var res = 0
while (right < nums.size - 1) {
var maxJump = 0
for (i in left..right) {
maxJump = maxOf(maxJump, i + nums[i])
}
left = right + 1
right = maxJump
res += 1
}
return res
}
}
/*
* O(N^2) DP + memoization
*/
class Solution {
fun jump(nums: IntArray): Int {
val dp = IntArray(nums.size) { 10001 }
fun jump(i: Int): Int {
if (i == nums.lastIndex)
return 0
if (dp[i] != 10001)
return dp[i]
for (steps in 1..nums[i]) {
if (i + steps <= nums.lastIndex) {
dp[i] = minOf(
dp[i],
1 + jump(i + steps)
)
}
}
return dp[i]
}
return jump(0)
}
}