簡體   English   中英

有沒有辦法打印一個列表的 2 個相等的子列表?

[英]Is there a way to print 2 equally sum sub list, of a list?

所以我在這里有這個代碼,如果有 2 個子列表具有相同的總和(總和的 1/2),則此代碼有效並返回 True,請閱讀有關分區相等子集總和的更多信息

例子:

s = Solution()
print(s.canPartition([3,10,9,2]))
# output [3, 9] , [10, 2]

我的代碼迭代索引,並且每次迭代拆分為 2 種方式 - 第一種方式是將值添加到 sum.. 第二種方式是繼續前進而不添加值。 如果其中一種方法返回 True,則表示已找到解決方案。

時間復雜度應該是 2^n,但由於動態規划,它已經減少到 O(n)

現在我試圖弄清楚的問題是如何回溯“真正的根”並打印屬於根的所有項目(希望是總和的一半)

我所說的“真根”的意思是,當我返回第一個真(這意味着我已經找到了總和)時,我已經有了這些項目。 例子:

[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

更好地理解我想要的 output 的示例:

s = Solution()
print(s.canPartition([3,10,9,2]))
# output [3, 9] , [10, 2]

一個有用的提示

您的helper function 要么返回True要么False 在它返回True之前,嘗試打印您在該遞歸中考慮的最后一個元素nums[i]

另一個提示

helper中,您正在進行兩次遞歸調用。

  1. helper(s1 + nums[i], s2, i + 1, memo)

  2. helper(s1, s2, i + 1, memo)

如果步驟 1. 的結果為True ,這意味着您將nums[i]保留在總和中。 您需要拆分該OR語句才能找出答案。 拆分時,如果 step 1. 為True ,則不需要運行 step 2。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM