【发布时间】:2020-08-11 11:20:12
【问题描述】:
所以我在这里有这段代码,如果有 2 个子列表的总和相同(总和的 1/2),它可以工作并返回 True 阅读更多关于Partition Equal Subset Sum
例子:
s = Solution()
print(s.canPartition([3,10,9,2]))
# output [3, 9] , [10, 2]
我的代码迭代索引,每次迭代分为两种方式 - 第一种方式是将值添加到 sum.. 第二种方式是继续前进而不添加值。 如果其中一种方法返回 True,则表示已找到解决方案。
时间复杂度应该是 2^n,但是由于动态规划,它已经减少到 O(n)
现在我试图弄清楚的问题是如何回溯“真正的根”并打印属于根的所有项目(希望是总数的一半)
我所说的“真正的根”的意思是,当我返回第一个 True(这意味着我已经找到了总和)时,我已经有了这些项目。 示例:
[3,10,9,2]
# output [3, 9] , [10, 2]
Tree of recursive:
[]
/ \
[3] []
/ \ \
[3,10] [3] []
/ / \
[3,9] # THE Root returing firt true
代码:
class Solution:
def canPartition(self, nums: List[int]) -> bool:
def helper(s1, s2, i, memo):
# recursion
hashed = (s1 + s2)
if hashed in memo.keys():
return memo[hashed]
if s1 == s2: # we have 2 groups of sums that sums total
return True
if s1 > s2: # we have too big group
return False
if i == len(nums): # the end
return s1 == s2
# 2 options : move to next index with/witohut counting index
memo[hashed] = helper(s1 + nums[i], s2, i + 1, memo) or helper(s1, s2, i + 1, memo)
return memo[hashed]
# begin
s = sum(nums) # sum
memo = {} # dynamic programing
if s % 2 == 0: # odd sum can't be divided equally
return helper(0, s // 2, 0, memo)
return False
更好地理解我想要的输出的示例:
s = Solution()
print(s.canPartition([3,10,9,2]))
# output [3, 9] , [10, 2]
【问题讨论】:
-
如果您能稍微解释一下您的代码,提出建议会更容易。什么是“真正的根”,属于它的项目是什么意思?
-
以递归方式,我不知道如何回溯列表,但是如果您将所有可能的分区创建到列表的 2 部分并比较位,您将拥有列表@ 987654322@
-
感谢@trigonom 我已经更新了更多细节。
标签: python algorithm recursion dynamic-programming subset-sum