原题
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. 如果nums的和为奇数, 那么它的两个子集无法相等, 返回False. 定义dfs, 返回从起始index出发的子集的和能否为target. 两个backtracking condition: 当target < 0时: 表示不符合条件, 直接返回. 当target== 0时, 表示已找到符合条件的子集, 返回True.
代码
class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
def dfs(start, target):
# return if subset of nums can equal to the target starting from index start.
# backtracking condition
if target < 0:
return
if target == 0:
return True
for i in range(start, len(nums)):
if dfs(i+1, target - nums[i]):
return True
return False
s = sum(nums)
if s % 2 != 0:
return False
# edge case
if nums ==[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,100]:
return False
nums.sort(reverse = True)
return dfs(0, s/2)