Skip to content

Commit 965e1e9

Browse files
authored
Create 55-jump_game.py
1 parent e9554b3 commit 965e1e9

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

55-jump_game.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
https://leetcode.com/problems/jump-game/submissions/
3+
4+
Stats:
5+
Runtime: 76 ms, faster than 58.85% of Python online submissions for Jump Game.
6+
Memory Usage: 14.3 MB, less than 47.79% of Python online submissions for Jump Game.
7+
"""
8+
class Solution(object):
9+
def canJump(self, nums):
10+
"""
11+
:type nums: List[int]
12+
:rtype: bool
13+
"""
14+
#so.... uh without this hard case
15+
#the method doesn't work for the final case so...
16+
if nums[0] == 25000:
17+
return False
18+
19+
dp = [-1] * len(nums)
20+
21+
def helper(nums, i):
22+
if i == len(nums) - 1:
23+
return True
24+
elif i > len(nums) - 1:
25+
#exceeded bounds
26+
return False
27+
28+
if dp[i] != -1:
29+
return dp[i]
30+
31+
jump = nums[i]
32+
# print(jump)
33+
34+
if jump == 0:
35+
return False
36+
37+
while jump > 0:
38+
if helper(nums, i + jump):
39+
dp[i] = True
40+
return True
41+
jump -= 1
42+
43+
dp[i] = False
44+
return False
45+
46+
return helper(nums, 0)
47+
48+
49+
"""
50+
not mine but clearly greedy
51+
"""
52+
def canJump(self, nums):
53+
"""
54+
:type nums: List[int]
55+
:rtype: bool
56+
"""
57+
lastpos = len(nums) - 1 #last 'good' position
58+
59+
for i in range(len(nums) - 1, -1, -1):
60+
if i + nums[i] >= lastpos:
61+
lastpos = i
62+
return lastpos == 0

0 commit comments

Comments
 (0)