herrDeng網內搜尋

自訂搜尋

Ads

2023年8月27日 星期日

C++/Python DP動態規劃與二元搜尋解Leetcode難題403 Frog Jump


C++/Python DP動態規劃與二元搜尋解Leetcode難題403 Frog Jump
使用遞迴結合記憶法來解決。這就是動態規劃(DP)。由於石頭的位置是按照升序排列的,因此要找到下一個可以跳躍的石頭,可以使用二元搜尋。
 ------------------------
 Use recursion with meomory to solve. That is DP. Since stones is in ascending order, to find the next stone for jump is using binary search. 


  1. class Solution:
  2. def canCross(self, stones: List[int]) -> bool:
  3. n=len(stones)
  4. @cache
  5. def f(i, k):
  6. if i==n-1: return True
  7. if i>=n: return False
  8. ans=False
  9. for jump in [k-1, k, k+1]:
  10. if jump==0: continue
  11. next= bisect_left(stones[i+1:], stones[i]+jump)+(i+1)
  12. if next==n or stones[next]!=stones[i]+jump: continue
  13. ans = ans or f(next, jump)
  14. return ans
  15. return f(0, 0)









沒有留言:

Related Posts Plugin for WordPress, Blogger...

熱門文章