在列表中选择唯一的组合

时间:2018-07-12 19:18:04

标签: python-3.x

我正在尝试生成唯一的数字组合,这些数字组合起来可以得出特定的目标:

 class Solution:
  def combinationSum(self, candidates, target):

    chosen = []
    res = []
    self.combinationHelper(candidates, chosen, target, res)

    return res

def combinationHelper(self, nums, chosen, target, res):
    if sum(chosen) > target:
        return
    if sum(chosen) == target:
        res.append([x for x in chosen])
    else:
        for i in range(0, len(nums)):
            chosen.append(nums[i])
            self.combinationHelper(nums, chosen, target, res)
            chosen.pop()

对于输入[2,3,5]target=8,我得到以下输出:

[2 2 2 2]

[2 3 3]

[3 2 3]

[3 3 2]

[3 5]

[5 3]

输出[2 3 3][3 3 2][3 2 3]相同(与[3,5][5,3])。

如何消除这些重复项?输出必须为list[list[int]]

2 个答案:

答案 0 :(得分:1)

使用settuple(您需要使用元组而不是列表,因为列表是可变的,因此不能是集合的项):

class Solution:
    def combinationSum(self, candidates, target):

      chosen = []
      res = set()
      self.combinationHelper(candidates, chosen, target, res)

      return [list(x) for x in res]

    def combinationHelper(self, nums, chosen, target, res):
        if sum(chosen) > target:
            return
        if sum(chosen) == target:
            res.add(tuple(sorted(chosen)))
        else:
            for i in range(0, len(nums)):
                chosen.append(nums[i])
                self.combinationHelper(nums, chosen, target, res)
                chosen.pop()

答案 1 :(得分:1)

添加排序的元组而不是列表。元组是 hashables ,因此您可以检查它们是否以前已经添加到res列表中。

只需更改

if sum(chosen) == target:
    res.append([x for x in chosen])

if sum(chosen) == target:
    v = tuple(sorted(chosen))
    if v not in res: res.append(v)

输出:

[(2, 2, 2, 2), (2, 3, 3), (3, 5)]

整个代码:

class Solution:
    def combinationSum(self, candidates, target):

        chosen = []
        res = []
        self.combinationHelper(candidates, chosen, target, res)

        return res

    def combinationHelper(self, nums, chosen, target, res):
        if sum(chosen) > target:
            return
        if sum(chosen) == target:
            v = tuple(sorted(x for x in chosen))
            if v not in res: res.append(v)
        else:
            for i in range(0, len(nums)):
                chosen.append(nums[i])
                self.combinationHelper(nums, chosen, target, res)
                chosen.pop()
Solution().combinationSum([2,3,5], 8)

此解决方案更适合小输入,例如您的输入。如果使用大数组,请指定,我们可以更改数据结构;)