forked from geemaple/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path55.jump-game.py
84 lines (66 loc) · 2.06 KB
/
55.jump-game.py
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
# greedy O(N)
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
last_pos = len(nums) - 1
for i in range(last_pos, -1, -1):
if i + nums[i] >= last_pos:
last_pos = i
return last_pos == 0
# DFS O(2^N)
class Solution_dfs(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return self.can_jump_from_position(0, nums)
def can_jump_from_position(self, pos, nums):
if pos == len(nums) - 1:
return True
furthest = min(len(nums), pos + nums[pos] + 1)
for i in range(pos + 1, furthest):
if self.can_jump_from_position(i, nums):
return True
return False
# DP top_down O(N^2)
class Solution_dp_top_down(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
table = [None for i in range(len(nums))]
table[-1] == True
return self.can_jump_from_position(0, nums, table)
def can_jump_from_position(self, pos, nums, memo):
if pos == len(nums) - 1:
return True
if memo[pos] != None:
return memo[pos]
furthest = min(len(nums), pos + nums[pos] + 1)
for i in range(pos + 1, furthest):
if self.can_jump_from_position(i, nums, memo):
memo[pos] = True
return True
memo[pos] = False
return False
# DP bottom_up O(N^2)
class Solution_dp_bottom_up(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
table = [None for i in range(len(nums))]
table[-1] = True
for i in range(len(nums) - 2, -1, -1):
furthest = min(len(nums), i + nums[i] + 1)
for j in range(i + 1, furthest):
if table[j]:
table[i] = True
break
return table[0] == True