Menu
CoddyTech

Combination Sum

中等回溯python iconjava iconcpp iconc iconjs icon+10

你会得到一个由不同正整数组成的列表 candidates,以及一个正整数 target。找出所有总和恰好等于 target 的候选数组合,每个候选数都可以使用任意次。[2, 3, 3] 和 [3, 2, 3] 是同一种组合。

将每种组合按升序排列,并按字典序排列这些组合:在两个组合首次出现不同的位置,值较小的组合排在前面。

函数

combinationSum(candidates: integer-array, target: integer) → integer-2d-array
candidatesinteger-array
你可以使用的不同值,顺序不限,每个值都可以使用任意多次
targetinteger
每种组合的总和都必须恰好达到
返回值integer-2d-array
所有和为目标值的组合,每个组合中的数字按升序排列,组合按字典序排列

约束条件

  • 1 ≤ candidates.length ≤ 50
  • 2 ≤ candidates[i] ≤ 500
  • 2 ≤ target ≤ 500
  • 所有 candidates 中的值都不相同,且没有特定顺序。
  • 至少有一种组合可以达到 target,且这样的组合最多有 150 种。

示例

输入
candidates = [6, 2, 3]target = 8
输出
[[2, 2, 2, 2], [2, 3, 3], [2, 6]]
解释
按第二个值排序,4 个 2、2 + 3 + 3 和 2 + 6 都能得到 8。不使用 2 时,只剩下 3 和 6,它们的和都是 3 的倍数,而 8 不是。
challenge icon

进阶

现在每个候选项最多只能使用一次,而且 candidates 中可能包含重复的值。你要如何修改搜索,才能避免同一种组合出现两次?

重置代码
def combinationSum(candidates, target):
    # 在这里编写代码

测试 #1

测试 #2

测试 #3

参数

candidates = [6, 2, 3]
target = 8

预期输出

[[2, 2, 2, 2], [2, 3, 3], [2, 6]]