【发布时间】:2020-03-19 08:07:21
【问题描述】:
您好,我已经为 LeetCode 上的分区相等子集问题 (https://leetcode.com/problems/partition-equal-subset-sum/) 起草了一个递归解决方案,该解决方案已被接受:
class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums or len(nums) < 2:
return False
if sum(nums) % 2 != 0:
return False
target = sum(nums) // 2
# if the maximum number in nums goes larger than target,
# then this maximum number cannot be partitioned into any subarray
# hence there's no solution in this case, return False early
if max(nums) > target:
return False
nums.sort(reverse = True)
return self.helper(nums, 0, target, 0)
def helper(self, nums, index, target, curr):
# since "target" value is derived from dividing total sum,
# we only need to search for one sum that makes target value in the array
# the rest is guaranteed to sum up to "target"
if curr == target:
return True
for i in range(index, len(nums)):
if curr + nums[i] > target:
continue
if self.helper(nums, i + 1, target, curr + nums[i]):
return True
return False
但是,作为后续行动,真正返回两个子集而不仅仅是 True/False 的最佳方法是什么。如果我必须更新上述现有代码,保存的子集的代码会是什么样子?我是那些开始使用 DP 的人之一。提前致谢。
【问题讨论】:
标签: python recursion dynamic-programming