Menu
CoddyTech

Combination Sum

MediumBacktrackingpython iconjava iconcpp iconc iconjs icon+10

You get a list candidates of different positive integers and a positive integer target. Find every combination of candidates that adds up to exactly target, using each candidate as many times as you like. [2, 3, 3] and [3, 2, 3] are the same combination.

Return each combination in ascending order, and the combinations in lexicographic order: at the first position where two combinations differ, the one with the smaller value comes first.

Function

combinationSum(candidates: integer-array, target: integer) → integer-2d-array
candidatesinteger-array
the different values you may use, in any order, each as many times as you like
targetinteger
the total every combination must reach exactly
Returnsinteger-2d-array
every combination that sums to target, each in ascending order, listed in lexicographic order

Constraints

  • 1 ≤ candidates.length ≤ 50
  • 2 ≤ candidates[i] ≤ 500
  • 2 ≤ target ≤ 500
  • All values in candidates are different, in no particular order.
  • At least one combination reaches target, and at most 150 do.

Examples

Input
candidates = [6, 2, 3]target = 8
Output
[[2, 2, 2, 2], [2, 3, 3], [2, 6]]
Explanation
Four 2s, 2 + 3 + 3 and 2 + 6 all make 8, ordered by their second value. Without a 2 only 3s and 6s are left, and their sums are multiples of 3, which 8 is not.
challenge icon

Follow-up

Each candidate may now be used at most once, and candidates may hold repeated values. How do you change the search so that no combination appears twice?

Reset code
def combinationSum(candidates, target):
    # Write code here

Test #1

Test #2

Test #3

Arguments

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

Expected Output

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