problem
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.
solution
这个问题可以转化为一个0-1背包问题,能否选出若干个数使得它们的和为sum(nums)/2。同时因为是“能否”而不是“最多”,因此可以在存储时使用bool值。
ps:动态规划时使用数组要比dict快,因为dict是接近于 O(1) .
ps1:关于背包问题可以参考背包问题九讲
class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
n = len(nums)
s = sum(nums)
if s % 2:
return False
else:
target = s // 2
d = [[False]*(target+1) for _ in range(n)]
for i in range(target+1):
d[0][i] = True if i == nums[0] else False
for i in range(1, n):#前i个物品
for j in range(target+1):#重量不超过j
d[i][j] = d[i-1][j] if j <= nums[i] else (d[i-1][j-nums[i]] or d[i-1][j])
if d[i][target]:
return True
return d[n-1][target]