-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0403-frog-jump.py
More file actions
32 lines (26 loc) · 865 Bytes
/
0403-frog-jump.py
File metadata and controls
32 lines (26 loc) · 865 Bytes
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
# time complexity: O(n)
# space complexity: O(nlogn)
from bisect import bisect_left
from functools import lru_cache
from typing import List
class Solution:
def canCross(self, stones: List[int]) -> bool:
n = len(stones)
@lru_cache(None)
def dp(i, k):
if i == n-1:
return True
ans = False
for jump in [k-1, k, k + 1]:
if jump == 0:
continue
next = bisect_left(stones[i+1:], stones[i] + jump) + (i + 1)
if next == n or stones[next] != stones[i] + jump:
continue
ans = ans or dp(next, jump)
return ans
return dp(0, 0)
stones = [0, 1, 3, 5, 6, 8, 12, 17]
print(Solution().canCross(stones))
stones = [0, 1, 2, 3, 4, 8, 9, 11]
print(Solution().canCross(stones))