动态规划只能说难得批爆 不看题解等着坐牢
416.分割等和子集
题目链接:https://leetcode.cn/problems/partition-equal-subset-sum/
class Solution:
def canPartition(self, nums: List[int]) -> bool:
if sum(nums) % 2 != 0:
return False
target = sum(nums) // 2
dp = [0]*10001
for i in range(len(nums)):
for j in range(target, nums[i]-1, -1):
dp[j] = max(dp[j], dp[j-nums[i]] + nums[i])
return target == dp[target]
1049.最后一块石头的重量II
题目链接:https://leetcode.cn/problems/last-stone-weight-ii/
class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
total = sum(stones)
dp = [0] * 15000
target = total // 2
for i in range(len(stones)):
for j in range(target, stones[i]-1, -1):
dp[j] = max(dp[j], dp[j-stones[i]] + stones[i])
return total - 2*dp[target]
494.目标和
题目链接:https://leetcode.cn/problems/target-sum/
很难 这种变种应用问题很难想出来目前
class Solution:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
total = sum(nums)
if abs(target) > total or (total + target) % 2 == 1: return 0
bagsize = (total + target) // 2
dp = [0]*(bagsize+1)
dp[0] = 1
for i in range(len(nums)):
for j in range(bagsize, nums[i]-1, -1):
dp[j] += dp[j-nums[i]]
return dp[bagsize]
后面这几题 弃疗了 直接复制了题解
474.一和零
题目链接:https://leetcode.cn/problems/ones-and-zeroes/
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[0] * (n + 1) for _ in range(m + 1)] # 默认初始化0
# 遍历物品
for str in strs:
ones = str.count('1')
zeros = str.count('0')
# 遍历背包容量且从后向前遍历!
for i in range(m, zeros - 1, -1):
for j in range(n, ones - 1, -1):
dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)
return dp[m][n]
518. 零钱兑换II
题目链接:https://leetcode.cn/problems/coin-change-ii/
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [0]*(amount + 1)
dp[0] = 1
# 遍历物品
for i in range(len(coins)):
# 遍历背包
for j in range(coins[i], amount + 1):
dp[j] += dp[j - coins[i]]
return dp[amount]
377.组和总和IV
题目链接:https://leetcode.cn/problems/combination-sum-iv/
class Solution:
def combinationSum4(self, nums: List[int], target: int) -> int:
dp = [0] * (target + 1)
dp[0] = 1
for i in range(1, target+1):
for j in nums:
if i >= j:
dp[i] += dp[i - j]
return dp[-1]