Combination Sum

Program for Combination Sum

You are given an array of unique numbers nums and a target number target. Your goal is to find all unique combinations of numbers from nums that add up to target.

You can use the same number from nums as many times as needed. Two combinations are considered the same only if they use the same numbers with the same frequency.

The order of numbers in the combinations doesn’t matter, and you can return the combinations in any order.

Combination Sum

Explanation:

  • 2 + 2 + 5 = 9. We use 2 twice, and 5 once.
  • 9 = 9. We use 9 once.

Constraints:

  • All elements of nums are distinct.
  • 1 <= nums.length <= 20
  • 2 <= nums[i] <= 30
  • 2 <= target <= 30

Program for Combinational Sum

Recommendation for Time and Space Complexity –The ideal solution should have a time complexity of O(2^(t/m)) and a space complexity of O(t/m), where t is the target value and m is the smallest number in the array.

Hints for solving problems

Hint 1 :

Think of the problem as a decision tree, where at each step, you have n options (n is the size of the array). Each path in the tree represents a possible combination. To stop building a path, consider a base condition related to the target value.

Hint 2 :

Use backtracking to explore all possible paths. Keep a variable sum that tracks the total of the chosen numbers in the current path. If sum == target, save a copy of the current combination to the result. Think about how to implement this recursive process.

Hint 3 :

Start traversing the array from index i in each recursive step. For each step, try selecting elements from index i to the end of the array. Extend the current path only if adding the element keeps sum <= target. Save the current path to the result whenever the target is reached.

There are mainly 2 approach to solve this problem-

  1. Backtracking Method
  2. Backtracking(Optimal) Method

1. Backtracking Method

This approach explores all possible combinations by recursively adding numbers to a current path and checking if their sum equals the target. If the sum exceeds the target, the recursion stops (backtracks) and tries other numbers. It ensures all potential solutions are explored.

  • Time complexity: O(2^(t/m))
  • Space complexity: O(t/m)

where t is the given target and m is the minimum value in nums.

Code

2. Backtracking(Optimal) Method

In this optimized approach, backtracking is enhanced by starting the recursive search only from the current index or later indices. This avoids duplicate combinations and reduces unnecessary computations, making the solution more efficient.

  • Time complexity: O(2^(t/m))
  • Space complexity: O(t/m)

Code

More Articles