赞
踩
class Solution:
def findArray(self, pref: List[int]) -> List[int]:
n = len(pref)
arr = [pref[0]]*n
for i in range(1,n):
arr[i] = pref[i]^pref[i-1]
return arr
class Solution:
def hardestWorker(self, n: int, logs: List[List[int]]) -> int:
s = 0
mx = -1
ans = inf
for i,lv in logs:
t= lv - s
if t > mx:
ans = i
mx = t
if t == mx:
ans = min(ans,i)
s = lv
return ans
dp预处理
class Solution: def robotWithString(self, s: str) -> str: n = len(s) f = ['z']*(n+1) # 每个字符后边最小的字符是谁 for i in range(n-1,-1,-1): f[i] = min(s[i],f[i+1]) ans = [] st = [] for i,c in enumerate(s): st.append(c) while st and st[-1] <= f[i+1]: ans.append(st.pop()) ans.extend(st[::-1]) return ''.join(ans)
counter预处理
class Solution: def robotWithString(self, s: str) -> str: cnt = [0]*26 for c in s: cnt[ord(c)-ord('a')] += 1 ans = [] j = 0 st = [] for c in s: while j < 26 and cnt[j]==0: j+=1 while st and ord(st[-1]) <= j+ord('a'): ans.append(st.pop()) if ord(c) == j + ord('a'): ans.append(c) else: st.append(c) cnt[ord(c)-ord('a')] -= 1 j = 0 ans.extend(st[::-1]) return ''.join(ans)
print(sys.getrecursionlimit())
在本题验证了一下,结果是550000。f[i][j][v] = f[i-1][j][(v-grid[i][j])%k) +f[i][j-1][(v-grid[i][j])%k)
f[0][0][grid[0][0]%k] = 1
,其他是0f[m-1][n-1][0]
记忆化搜索+cache_clear
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: MOD = 10**9+7 m,n = len(grid),len(grid[0]) @cache def f(i,j,mod): if i == j == 0: return int(grid[0][0]%k == mod%k) ans = 0 if i: ans += f(i-1,j,(mod-grid[i][j])%k) if j : ans += f(i,j-1,(mod-grid[i][j])%k) return ans%MOD ans = f(m-1,n-1,k) f.cache_clear() # print(sys.getrecursionlimit()) return ans
滚动优化DP
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: MOD = 10**9+7 m,n = len(grid),len(grid[0]) f = [[0]*k for _ in range(n)] f[0][grid[0][0]%k] = 1 for i in range(m): g = f f = [[0]*k for _ in range(n)] for j in range(n): if i == j == 0: f[0][grid[0][0]%k]=1 continue for x in range(k): if i: f[j][x] += g[j][(x-grid[i][j])%k] if j: f[j][x] += f[j-1][(x-grid[i][j])%k] f[j][x]%=MOD return f[-1][0]%MOD
朴素DP
class Solution: def numberOfPaths(self, grid: List[List[int]], k: int) -> int: MOD = 10**9+7 m,n = len(grid),len(grid[0]) f = [[[0]*k for _ in range(n)] for _ in range(m)] f[0][0][grid[0][0]%k] = 1 for i in range(m): for j in range(n): if i == j == 0: continue for x in range(k): if 0<=i-1<m and 0<=j<n: f[i][j][x] += f[i-1][j][(x-grid[i][j])%k] if 0<=i<m and 0<=j-1<n: f[i][j][x] += f[i][j-1][(x-grid[i][j])%k] f[i][j][x]%=MOD return f[-1][-1][0]%MOD
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。