前言
继续leetcode刷题生涯
这里记录的都是笔者觉得有点意思的做法
参考了好几位大佬的题解,尤其是powcai大佬和labuladong大佬,感谢各位大佬
312. 戳气球
# 动态规划
class Solution:
def maxCoins(self, nums: List[int]) -> int:
nums = [1] + nums + [1]
n = len(nums)
dp = [[0] * n for _ in range(n)]
for k in range(2, n):
for i in range(n - k):
j = i + k
for t in range(i + 1, j):
dp[i][j] = max(dp[i][j], nums[i] * nums[t] * nums[j] + dp[i][t] + dp[t][j])
return dp[0][n - 1]
313. 超级丑数
# 动态规划
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
uglies = [0] * n
primes_to_uglies_loc = [0] * len(primes)
uglies[0] = 1
for i in range(1, n):
uglies[i] = min(x * uglies[y] for x, y in zip(primes, primes_to_uglies_loc))
for j in range(len(primes)):
if uglies[i] >= primes[j] * uglies[primes_to_uglies_loc[j]]:
primes_to_uglies_loc[j] += 1
return uglies[-1]
315. 计算右侧小于当前元素的个数
# 二分
class Solution:
def countSmaller(self, nums: List[int]) -> List[int]:
import bisect
queue = []
res = []
for num in nums[::-1]:
loc = bisect.bisect_left(queue, num)
res.append(loc)
queue.insert(loc, num)
return res[::-1]
# 这个方法有点妙
316. 去除重复字母
# 递归
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
# 先按字典排序
for a in sorted(set(s)):
tmp = s[s.index(a):]
# 看余下的是否能组成所需的字母
if len(set(tmp)) == len(set(s)):
return a + self.removeDuplicateLetters(tmp.replace(a, ""))
return ""
# 迭代
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
res = ""
while s:
# 从右往左找,找到最小位置的索引号
loc = min(map(s.rindex, s))
# 找该索引前面最小的字母
a = min(s[:loc + 1])
res += a
s = s[s.index(a):].replace(a, "")
return res
# 栈
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
from collections import Counter
c = Counter(s)
stack = []
existed = set()
for a in s:
if a not in existed:
# 判断后面还有没有该字母
while stack and stack[-1] > a and c[stack[-1]] > 0:
existed.remove(stack.pop())
stack.append(a)
existed.add(a)
c[a] -= 1
return "".join(stack)
318. 最大单词长度乘积
# 二进制+哈希
class Solution:
def maxProduct(self, words: List[str]) -> int:
from collections import defaultdict
lookup = defaultdict(int)
for i in range(len(words)):
mask = 0
for alp in words[i]:
mask |= 1 << (ord(alp) - 97)
lookup[mask] = max(lookup[mask], len(words[i]))
return max([lookup[x] * lookup[y] for x in lookup for y in lookup if not x & y] or [0])
# 妙啊
319. 灯泡开关
# 这是道数学题
from math import sqrt
class Solution:
def bulbSwitch(self, n: int) -> int:
return int(sqrt(n))