Update 0416.分割等和子集.md

This commit is contained in:
jianghongcheng
2023-06-04 05:36:45 -05:00
committed by GitHub
parent 37fdbd369e
commit 5ab0a94c71

View File

@ -296,62 +296,85 @@ false true false false false true true false false false true true
``` ```
### Python ### Python
卡哥版
```python ```python
# 一维度数组解法
class Solution: class Solution:
def canPartition(self, nums: List[int]) -> bool: def canPartition(self, nums: List[int]) -> bool:
target = sum(nums) _sum = 0
if target % 2 == 1: return False
target //= 2
dp = [0] * (target + 1)
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]
```
```python # dp[i]中的i表示背包内总和
# 二维度数组解法 # 题目中说:每个数组中的元素不会超过 100数组的大小不会超过 200
class Solution: # 总和不会大于20000背包最大只需要其中一半所以10001大小就可以了
def canPartition(self, nums: List[int]) -> bool: dp = [0] * 10001
target = sum(nums) for num in nums:
nums = sorted(nums) _sum += num
# 也可以使用内置函数一步求和
# _sum = sum(nums)
if _sum % 2 == 1:
return False
target = _sum // 2
# 做最初的判断 # 开始 0-1背包
if target % 2 != 0: for num in nums:
for j in range(target, num - 1, -1): # 每一个元素一定是不可重复放入,所以从大到小遍历
dp[j] = max(dp[j], dp[j - num] + num)
# 集合中的元素正好可以凑成总和target
if dp[target] == target:
return True
return False return False
# 找到 target value 可以认为这个是背包的体积 ```
target = target // 2 二维DP版
```python
class Solution:
def canPartition(self, nums: List[int]) -> bool:
row = len(nums) total_sum = sum(nums)
col = target + 1
# 定义 dp table if total_sum % 2 != 0:
dp = [[0 for _ in range(col)] for _ in range(row)] return False
# 初始 dp value target_sum = total_sum // 2
for i in range(row): dp = [[False] * (target_sum + 1) for _ in range(len(nums) + 1)]
dp[i][0] = 0
for j in range(1, target): # 初始化第一行空子集可以得到和为0
if nums[0] <= j: for i in range(len(nums) + 1):
dp[0][j] = nums[0] dp[i][0] = True
# 遍历 先遍历物品再遍历背包 for i in range(1, len(nums) + 1):
for i in range(1, row): for j in range(1, target_sum + 1):
if j < nums[i - 1]:
cur_weight = nums[i] # 当前数字大于目标和时,无法使用该数字
cur_value = nums[i]
for j in range(1, col):
if cur_weight > j:
dp[i][j] = dp[i - 1][j] dp[i][j] = dp[i - 1][j]
else: else:
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - cur_weight] + cur_value) # 当前数字小于等于目标和时,可以选择使用或不使用该数字
dp[i][j] = dp[i - 1][j] or dp[i - 1][j - nums[i - 1]]
return dp[len(nums)][target_sum]
```
一维DP版
```python
class Solution:
def canPartition(self, nums: List[int]) -> bool:
total_sum = sum(nums)
if total_sum % 2 != 0:
return False
target_sum = total_sum // 2
dp = [False] * (target_sum + 1)
dp[0] = True
for num in nums:
# 从target_sum逆序迭代到num步长为-1
for i in range(target_sum, num - 1, -1):
dp[i] = dp[i] or dp[i - num]
return dp[target_sum]
# 输出结果
return dp[-1][col - 1] == target
``` ```
### Go ### Go