如何将此递归解决方案转换为 DP 解决方案?
Posted
技术标签:
【中文标题】如何将此递归解决方案转换为 DP 解决方案?【英文标题】:How do I turn this recursive solution to a DP solution? 【发布时间】: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 的人之一。提前致谢。
【问题讨论】:
【参考方案1】:想出了解决办法:
class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums or len(nums) < 2:
return []
if sum(nums) % 2 != 0:
return []
target = sum(nums) // 2
if max(nums) > target:
return []
nums.sort(reverse = True)
res = []
self.helper(nums, 0, target, [], res)
return res
def helper(self, nums, index, target, curr, res):
if sum(curr) == target:
res.append(list(curr))
return
for i in range(index, len(nums)):
if sum(curr) + nums[i] > target:
continue
self.helper(nums, i + 1, target, curr + [nums[i]], res)
【讨论】:
以上是关于如何将此递归解决方案转换为 DP 解决方案?的主要内容,如果未能解决你的问题,请参考以下文章
Python 3.3 如何将此递归函数转换为纯 yield 循环版本?
如何将此基于 ReactJS 类的组件转换为基于函数的组件?