From 88750b119003658587b9e03ff3b6f0e525d665c2 Mon Sep 17 00:00:00 2001 From: Logen <47022821+Logenleedev@users.noreply.github.com> Date: Mon, 23 Jan 2023 17:43:15 -0600 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=8C=E7=BB=B4=E6=95=B0?= =?UTF-8?q?=E7=BB=84=E8=A7=A3=E6=B3=95=20+=20=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0416.分割等和子集.md | 47 ++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/problems/0416.分割等和子集.md b/problems/0416.分割等和子集.md index ecee1d83..936ba270 100644 --- a/problems/0416.分割等和子集.md +++ b/problems/0416.分割等和子集.md @@ -291,18 +291,63 @@ false true false false false true true false false false true true ### Python: ```python +# 一维度数组解法 class Solution: def canPartition(self, nums: List[int]) -> bool: target = sum(nums) if target % 2 == 1: return False target //= 2 - dp = [0] * 10001 + dp = [0] * (len(nums) + 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 +# 二维度数组解法 +class Solution: + def canPartition(self, nums: List[int]) -> bool: + target = sum(nums) + nums = sorted(nums) + + # 做最初的判断 + if target % 2 != 0: + return False + + # 找到 target value 可以认为这个是背包的体积 + target = target // 2 + + row = len(nums) + col = target + 1 + + # 定义 dp table + dp = [[0 for _ in range(col)] for _ in range(row)] + + # 初始 dp value + for i in range(row): + dp[i][0] = 0 + + for j in range(1, target): + if nums[0] <= j: + dp[0][j] = nums[0] + + # 遍历 先遍历物品再遍历背包 + for i in range(1, row): + + 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] + else: + dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - cur_weight] + cur_value) + + # 输出结果 + return dp[-1][col - 1] == target +``` + ### Go: ```go // 分割等和子集 动态规划