Day 38 动态规划 part04
1道题目
416. 分割等和子集
解题理解
01背包问题,二维DP的写法还算勉强理解,一维直接看不懂了。
class Solution:
def canPartition(self, nums: List[int]) -> bool:
total_num = sum(nums)
if total_num % 2 != 0:
return False
target = total_num // 2
dp = [0] * (target + 1)
for num in nums:
for j in range(target, num - 1, -1):
dp[j] = max(dp[j], dp[j - num] + num)
if dp[target] == target:
return True
return False