Advertisement
goodwish

ways are you still at index 0

Nov 8th, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. Q: https://leetcode.com/discuss/interview-question/416381/Google-Phone-Interview-Question-DP
  2.  
  3. https://leetcode.com/problems/number-of-ways-to-stay-in-the-same-place-after-some-steps/submissions/
  4.  
  5. class Solution:
  6.     def numWays(self, steps: int, arrLen: int) -> int:
  7.         # init, f(n, h), f[i][j], 状态: i step at idx j.
  8.         if arrLen > steps:
  9.             arrLen = steps//2 + 1
  10.         w = arrLen
  11.         n = steps
  12.         MOD = 10**9 + 7
  13.         f = [[0] * (w + 1) for _ in range(n + 1)]
  14.         f[0][1] = 1
  15.        
  16.         for i in range(1, n + 1):
  17.             for j in range(1, w + 1):
  18.                 f[i][j] += f[i - 1][j]
  19.                 if j > 1:
  20.                     f[i][j] += f[i - 1][j - 1]
  21.                 if j < w:
  22.                     f[i][j] += f[i - 1][j + 1]
  23.                 f[i][j] %= MOD
  24.         return f[n][1]
  25.  
  26. # ...x.
  27. # .....
  28. # x.
  29. # ..
  30. # 最后一步 last step: from left, from right, stay.
  31. # 注意 0, w - 1 的时候, 左右越界情况.
  32.  
  33. o = Solution()
  34. ans = o.BackWays(w=3, n = 3)
  35. ans = o.BackWays(w=5, n = 12)
  36. print(ans)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement