455. 分发饼干
这题使用贪心,为了获得喂饱孩子的最大值,优先满足胃口小的孩子,所以需要对孩子的胃口值进行一个升序的排列。为了不浪费cookie也优先使用分量最小的cookie去满足孩子的胃口,所以对饼干的份量也按升序排列。具体实现如下
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
g.sort()
s.sort()
childIndex = 0
for cookie in s:
if childIndex >= len(g):
break
if g[childIndex] <= cookie:
childIndex += 1
return childIndex
376. 摆动序列
这题允许对数组进行删除操作,所以找到所有局部峰值的个数即为全局最优解。不过考虑到可能的平坡情况,我们可以在摆动更新的时候再更新preDif
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
curDiff = 0
preDiff = 0
res = 1
for i in range(len(nums)-1):
curDiff = nums[i+1] - nums[i]
if (curDiff > 0 and preDiff <= 0) or (curDiff < 0 and preDiff >= 0):
res += 1
preDiff = curDiff
return res
53. 最大子数组和
这题每次取pre加上当前值之后的大小与pre相比之间的最大值,res每次保留pre与res中的最大值。
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
pre = float("-inf")
res = float("-inf")
for i in nums:
pre = max(pre+i,i)
res = max(pre,res)
return res
51. N 皇后
这道题需要回溯加上一个验证算法。我们一行一行的加皇后,每一行相当于一层,每层相当于有n个选项。因为我们是按行从上到下放置皇后,那么我们在写验证算法的时候,只需要判断要放置的该列是否存在皇后,以及该格子的45度角与135度角是否有皇后存在。具体实现如下
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
res = []
subset = [["."] * n for _ in range(n)]
def isValid(row,col):
for i in range(row):
if subset[i][col] == "Q":
return False
i,j = row-1,col-1
while i >= 0 and j >= 0:
if subset[i][j] == "Q":
return False
i-=1
j-=1
i,j = row-1,col+1
while i >= 0 and j < n:
if subset[i][j] == "Q":
return False
i-=1
j+=1
return True
def BackTrack(row):
if row == n:
res.append(["".join(i) for i in subset])
return
for col in range(n):
if isValid(row,col):
subset[row][col] = "Q"
BackTrack(row+1)
subset[row][col] = "."
BackTrack(0)
return res