Combination Sum

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code
  • Pro

Write combinationSum(candidates, target): candidates holds 1 to 30 different whole numbers from 2 to 40, in any order, and you may reorder it; target is a whole number from 1 to 40. Return every combination of candidates adding up to target, using each number any number of times. Write each combination in ascending order and list each once: [2, 2, 3] and [2, 3, 2] are the same. The combinations can come in any order; return [] when none adds up. For example, combinationSum([2, 3, 6, 7], 7) is [[2, 2, 3], [7]], in either order. The checks include a target of 40, so building every ordering and then dropping repeats is too slow.

Your code must pass

  • Finds every combination for [2, 3, 6, 7] and 7
  • Reuses a number as often as needed
  • Returns an empty array when nothing adds up
  • Lists each combination once, in ascending order
  • Is fast enough for a target of 40