/39. Combination Sum

39. Combination Sum

Medium
Arrays76.2% acceptance

Given a list of distinct positive integers num_set and a positive integer sum_goal, return all unique lists of elements from num_set (with unlimited repetitions allowed) whose elements sum to sum_goal. Each combination must be unique in terms of frequency of elements. The order of combinations and elements within each combination does not matter.

Example 1

Input: num_set = [4, 5, 9], sum_goal = 9

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

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

Example 2

Input: num_set = [3, 6], sum_goal = 12

Output: [[3,3,3,3],[6,6],[3,3,6]]

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

Example 3

Input: num_set = [7], sum_goal = 14

Output: [[7,7]]

Explanation: Only one combination: [7,7].

Constraints

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

Case 1

Input: num_set = [5, 8], sum_goal = 13

Expected: [[5,8]]

Case 2

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

Expected: [[2,2,2,2],[4,4],[2,2,4]]

Case 3

Input: num_set = [10], sum_goal = 5

Expected: []

Case 4

Input: num_set = [1, 3, 4], sum_goal = 5

Expected: [[1,1,1,1,1],[1,1,3],[1,4],[3,1,1],[3,1,1]]