[LeetCode416. Partition Equal Subset Sum]
给定一个非负数组,是否可以将其分成两个和相等的子数组。
Example 1:
Input: [1, 5, 11, 5]
Output: true
Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5]
Output: false
Explanation: The array cannot be partitioned into equal sum subsets.
动态规划
首先,如果数组和为奇数,显然不可对半分。
其次,我们定义一个大小为(数组和sum+1)的数组dp,dp的每个元素记录当前位置index是否可以由nums中的数相加得到。
最后,我们只需要判断dp[sum // 2]是否为True,即可判断是否可以对半分。
class Solution:
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
sum_all = sum(nums)
if sum_all % 2:
return False
target = sum_all // 2
dp = [0 for i in range(sum_all + 1)]
dp[0] = 1
for num in nums:
for i in range(target, -1, -1):
if dp[i]:
dp[i + num] = 1
if dp[target]