【问题标题】:How do I turn this recursive solution to a DP solution?如何将此递归解决方案转换为 DP 解决方案?
【发布时间】: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


    【解决方案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)
    
    
    

    【讨论】:

      猜你喜欢
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 2021-12-15
      • 2020-05-22
      相关资源
      最近更新 更多