forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jump-game-vii.py
48 lines (43 loc) · 1.12 KB
/
jump-game-vii.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
# Time: O(n)
# Space: O(n)
# dp with line sweep solution
class Solution(object):
def canReach(self, s, minJump, maxJump):
"""
:type s: str
:type minJump: int
:type maxJump: int
:rtype: bool
"""
dp = [False]*len(s)
dp[0] = True
cnt = 0
for i in xrange(1, len(s)):
if i >= minJump:
cnt += dp[i-minJump]
if i > maxJump:
cnt -= dp[i-maxJump-1]
dp[i] = cnt > 0 and s[i] == '0'
return dp[-1]
# Time: O(n)
# Space: O(n)
import collections
# bfs solution
class Solution2(object):
def canReach(self, s, minJump, maxJump):
"""
:type s: str
:type minJump: int
:type maxJump: int
:rtype: bool
"""
q = collections.deque([0])
reachable = 0
while q:
i = q.popleft()
for j in xrange(max(i+minJump, reachable+1), min(i+maxJump+1, len(s))):
if s[j] != '0':
continue
q.append(j)
reachable = i+maxJump
return i == len(s)-1