[416][中等][动态规划][背包] 分割等和子集
题目描述
输入: [1, 5, 11, 5]
输出: true
解释: 数组可以分割成 [1, 5, 5] 和 [11].输入: [1, 2, 3, 5]
输出: false
解释: 数组不能分割成两个元素和相等的子集.解题思路
恰好装满
最后更新于
输入: [1, 5, 11, 5]
输出: true
解释: 数组可以分割成 [1, 5, 5] 和 [11].输入: [1, 2, 3, 5]
输出: false
解释: 数组不能分割成两个元素和相等的子集.最后更新于
class Solution:
def canPartition(self, nums: List[int]) -> bool:
n = len(nums)
total = sum(nums)
if total % 2 == 1:
return False
target = total // 2
cache = [0] * (target + 1)
for i in range(n):
for j in range(target, nums[i] - 1, -1):
cache[j] = max(cache[j], cache[j - nums[i]] + nums[i])
return cache[-1] == targetdp[i][j] = dp[i - 1][j] or dp[i - 1][j - w[i]]class Solution:
def canPartition(self, nums: List[int]) -> bool:
n = len(nums)
total = sum(nums)
if total % 2 == 1:
return False
target = total // 2
cache = [False] * (target + 1)
cache[0] = True
for i in range(n):
for j in range(target, nums[i] - 1, -1):
cache[j] = cache[j] or cache[j - nums[i]]
return cache[-1]