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 whose values add up to exactly target, where each candidate may be used as many times as you like. Two combinations are the same when they use the same values the same number of times, so [2, 3, 3] and [3, 2, 3] count once.

Return each combination with its values in ascending order, and the combinations in lexicographic order: compare two combinations value by value from the left, and the one with the smaller value at the first difference 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 make 8, and so do 2 + 3 + 3 and 2 + 6. All three start with 2, so the second value sets the order: 2, then 3, then 6. Without a 2 you only have 3s and 6s, and every mix of those is a multiple of 3, which 8 is not.

lock icon+12 hidden tests on Submit

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 cases

Case 1

Case 2

Case 3

Input

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

Expected

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