Given an integer array nums
, return true
if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or false
otherwise.
Example 1:
Input: nums = [1,5,11,5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and [11].
这个问题可以转化为0-1背包问题,在这里重量和价值是一样的,因为我们求子数组的和。
定义状态dp[w]表示:从数组nums中选择一些元素,放入最多能装元素和为w的背包中得到的元素和最大为多少。如果最大和为w,即数组和的一半那么就可以分割。
class Solution:
def zeroOnePackMethod(self, weight, value, W):
size = len(weight)
dp = [0 for _ in range(W+1)]
for i in range(size+1):
for w in range(W, w[i-1]-1, -1):
dp[w] = min(dp[w], dp[w-weight[i-1]] + value[i-1])
return dp[W]
def canPartition(self, nums: List[int]) -> bool:
if sum(nums) & 1:
return False
target = sum(nums)//2
return self.zeroOnePackMethod(nums, nums, target)