这次只做出一题,也就是第一题。其他题参考大佬们的写法。
1、用栈操作构建数组
题目描述:
https://leetcode-cn.com/contest/weekly-contest-188/problems/build-an-array-with-stack-operations/
题解:
class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
tlist = [ ]
res = []
for i in range(1,n+1):
tlist.append(i)
while target:
temp = tlist.pop(0)
if temp == target[0]:
res.append("Push")
target.pop(0)
else:
res.append("Push")
res.append("Pop")
return res
2、形成两个异或相等数组的三元组数目
题目描述:
https://leetcode-cn.com/contest/weekly-contest-188/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/
题解:
class Solution:
def countTriplets(self, arr: List[int]) -> int:
pre = 0
cnt = collections.defaultdict(list)
cnt[0].append(-1)
res = 0
for i, a in enumerate(arr):
pre ^= a
for p in cnt[pre]:
res += i - p - 1
cnt[pre].append(i)
return res
或:
class Solution:
def countTriplets(self, arr: List[int]) -> int:
count = 0
for i in range(len(arr)):
for j in range(i + 1,len(arr)):
a = arr[i]
b = 0
for k in range(i + 1,j):
a ^= arr[k]
for k in range(j,len(arr)):
b ^= arr[k]
if a == b:
count += 1
return count
class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
temp = collections.defaultdict(list)
for a,b in edges:
temp[a].append(b)
def dfs(num):
res = 0
apple = hasApple[num]
for c in temp[num]:
r,a = dfs(c)
if a:
res += 2 + r
apple = apple or a
return res,apple
return dfs(0)[0]
4、切披萨的方案数
题目描述:
https://leetcode-cn.com/contest/weekly-contest-188/problems/number-of-ways-of-cutting-a-pizza/
题解:
class Solution:
def ways(self, pizza: List[str], k: int) -> int:
mod = 10**9 + 7
memo = {}
rightdowncnt = collections.defaultdict(int)
downcnt = collections.defaultdict(int)
rightcnt = collections.defaultdict(int)
rows, cols = len(pizza), len(pizza[0])
# 预处理, 求三种cnt字典
for c in range(cols):
for r in range(rows)[::-1]:
downcnt[r, c] = 1 if pizza[r][c] == 'A' else 0
downcnt[r, c] += downcnt[r + 1, c]
for r in range(rows):
for c in range(cols)[::-1]:
rightcnt[r, c] = 1 if pizza[r][c] == 'A' else 0
rightcnt[r, c] += rightcnt[r, c + 1]
for r in range(rows)[::-1]:
for c in range(cols)[::-1]:
rightdowncnt[r, c] = 1 if pizza[r][c] == 'A' else 0
rightdowncnt[r,
c] += rightdowncnt[r + 1, c] + rightcnt[r, c + 1]
def dfs(r, c, p):
# 递归出口
if r == rows or c == cols:
return 0
if (r, c, p) not in memo:
if rightdowncnt[r, c] < p:
# 剪枝
memo[r, c, p] = 0
elif p == 1:
# 只有1人时方案数只能为1
memo[r, c, p] = 1
else:
sm = 0
cnt = 0
# 状态转移, 求接下来所有可能的方案数之和
# 注意取模
for nexr in range(r+1, rows):
cnt += rightcnt[nexr-1, c]
if cnt > 0:
sm = (sm + dfs(nexr, c, p - 1)) % mod
cnt = 0
for nexc in range(c+1, cols):
cnt += downcnt[r, nexc-1]
if cnt > 0:
sm = (sm + dfs(r, nexc, p - 1)) % mod
memo[r, c, p] = sm
return memo[r, c, p]
res = dfs(0, 0, k)
return res