目录
学习目标
学习内容
416. 分割等和子集
学习目标
- 01背包问题,你该了解这些!
- 01背包问题,你该了解这些! 滚动数组
- 416. 分割等和子集
学习内容
problems/背包理论基础01背包-1.md · programmercarl/leetcode-master(代码随想录出品) - Gitee.comhttps://gitee.com/programmercarl/leetcode-master/blob/master/problems/%E8%83%8C%E5%8C%85%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%8001%E8%83%8C%E5%8C%85-1.md
problems/背包理论基础01背包-2.md · programmercarl/leetcode-master(代码随想录出品) - Gitee.comhttps://gitee.com/programmercarl/leetcode-master/blob/master/problems/%E8%83%8C%E5%8C%85%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%8001%E8%83%8C%E5%8C%85-2.md
416. 分割等和子集
416. 分割等和子集 - 力扣(LeetCode)https://leetcode.cn/problems/partition-equal-subset-sum/
class Solution:
def canPartition(self, nums: List[int]) -> bool:
target = sum(nums)
if target%2==1:return False
n = len(nums)
dp=[[0]*(target//2+1)for _ in range(n+1)]
for i in range(1,n+1):
for j in range(target//2+1):
if j<nums[i-1]:
dp[i][j] = dp[i-1][j]
else:
dp[i][j] = max(dp[i-1][j],dp[i-1][j-nums[i-1]]+nums[i-1])
if dp[i][-1]==target//2:return True
return False
class Solution:
def canPartition(self, nums: List[int]) -> bool:
target = sum(nums)
if target%2==1:return False
n = len(nums)
dp=[0]*(target//2+1)
for i in range(n):
for j in range(target//2,nums[i-1]-1,-1):
dp[j] = max(dp[j],dp[j-nums[i-1]]+nums[i-1])
if dp[-1]==target//2:return True
return False