CodePark/ problems / Make the Total
START PRACTICINGPRACTICE
Coding problem · Data structures and algorithms › Backtracking

Make the Total

mediumabout 25 minutes in an interview

candidates holds distinct positive integers, and target is a positive integer. Find every group of candidates that adds up to exactly target, and return them all.

  • A group can use the same candidate again and again, or skip it.
  • Only how many of each number a group holds matters, not their order. [3, 5] and [5, 3] are one group, so list it once.
  • Order doesn't matter anywhere: not the order of groups in the result, and not the order of numbers inside a group.
  • If no group reaches target, return [].
  • candidates has 1 to 10 numbers, each between 1 and 30, in any order. target is between 1 and 30.
Input: candidates = [3, 4, 5], target = 8 Output: [[3, 5], [4, 4]]4 is used twice. [5, 3] is the same combination as [3, 5].
Input: candidates = [2, 3, 5], target = 10 Output: [[2, 2, 2, 2, 2], [2, 2, 3, 3], [2, 3, 5], [5, 5]]
Input: candidates = [4, 6], target = 5 Output: []Every sum of 4s and 6s is even, so no sum can be odd.