/39. Combination Sum

39. Combination Sum

Medium
Arrays76.2% acceptance

Given an array of distinct positive integers num_choices and a positive integer sum_goal, return all unique combinations of elements from num_choices (each element can be used unlimited times) such that the sum of the elements in each combination equals sum_goal. Each combination must be unique based on the frequency of elements, and the order of elements within a combination does not matter. Return the list of combinations in any order.

Example 1

Input: num_choices = [4, 5, 9], sum_goal = 13

Output: [[4,4,5],[4,9],[5,4,4],[9,4]]

Explanation: Possible combinations: [4,4,5], [4,9], [5,4,4], [9,4].

Example 2

Input: num_choices = [3, 7], sum_goal = 10

Output: [[3,7],[3,3,3,3]]

Explanation: Possible combinations: [3,7], [3,3,3,3].

Example 3

Input: num_choices = [6], sum_goal = 5

Output: []

Explanation: No combination sums to 5.

Constraints

  • 1 <= len(num_choices) <= 30
  • 2 <= num_choices[i] <= 40
  • All elements in num_choices are distinct
  • 1 <= sum_goal <= 40
Python (current runtime)

Case 1

Input: num_choices = [5, 8], sum_goal = 16

Expected: [[8,8],[5,5,6]]

Case 2

Input: num_choices = [2, 4, 7], sum_goal = 8

Expected: [[2,2,2,2],[2,2,4],[4,4],[7,1]]

Case 3

Input: num_choices = [10, 11], sum_goal = 21

Expected: [[10,11]]