51.N皇后
题目链接:https://leetcode.cn/problems/n-queens/
这道题目得了解皇后站位规则,规划好边界后就好做题了
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
if not n:
return[]
chessboard = [['.']*n for _ in range(n)]
res = []
def isValid(chessboard, row, col):
#check row
for i in range(len(chessboard)):
if chessboard[i][col] == 'Q':
return False
#check top left corner
i = row-1
j = col-1
while i>=0 and j>=0:
if chessboard[i][j] == 'Q':
return False
i -= 1
j -= 1
#check top right corner
i = row-1
j = col+1
while i>=0 and j<len(chessboard):
if chessboard[i][j] == 'Q':
return False
i -= 1
j += 1
return True
def backtracking(chessboard, row, n):
if row == n:
temp_res = []
for temp in chessboard:
tempstr = ''.join(temp)
temp_res.append(tempstr)
res.append(temp_res)
for col in range(n):
if not isValid(chessboard, row, col):
continue
chessboard[row][col] = 'Q'
backtracking(chessboard, row+1, n)
chessboard[row][col] = '.'
backtracking(chessboard, 0, n)
return res
455.分发饼干
题目链接:https://leetcode.cn/problems/assign-cookies/
很典型的贪心问题,从局部最优 推全局最优
class Solution:
def findContentChildren(self, g: List[int], s: List[int]) -> int:
s.sort()
g.sort()
count = 0
for i in range(len(s)):
if count < len(g) and s[i] >= g[count]:
count += 1
return count
376.摆动序列
题目链接:https://leetcode.cn/problems/wiggle-subsequence/
当加和为0或者负数时,就毫无意义。
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
pre_s, cur_s, count = 0, 0, 1
for i in range(len(nums)-1):
cur_s = nums[i+1] - nums[i]
if cur_s * pre_s <= 0 and cur_s != 0:
count += 1
pre_s = cur_s
return count
53.最大子数组和
题目链接:https://leetcode.cn/problems/maximum-subarray/
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
result = -float('inf')
count = 0
for i in range(len(nums)):
count += nums[i]
if count > result:
result = count
if count <= 0:
count = 0
return result
今天的三道贪心题目 都是很典型的贪心应用
还有复习任务 先复习了 溜了