Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Note:
- Each of the array element will not exceed 100.
- The array size will not exceed 200.
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.
这道题可以说非常好,我想到两种方法,第一种是dfs,current sum==target sum就return True,否则for i in range(len(nums)),每次选一个num[i]加到current sum里,然后nums变为nums[:i]+nums[i+1:],进行递归。
可惜啊,这方法超时了。
于是乎,咱们直接上dp。说到dp这题是subset sum的变种题。
图表:
横坐标是amount也就是target sum,纵坐标是nums,dp规则见代码。就这样~
class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
totalsum=sum(nums)
if totalsum%2:
return False
targetsum=totalsum/2
mem=[[False for _ in range(targetsum+1)] for _ in range(len(nums))]
for r in range(len(nums)):
mem[r][0]=True
for r in range(len(nums)):
for c in range(1,targetsum+1):
if nums[r]>c:
mem[r][c]=mem[r-1][c]
else:
if mem[r-1][c]:
mem[r][c]=True
else:
mem[r][c]=mem[r-1][c-nums[r]]
return mem[-1][-1]