Combination Sum II

Program for Printing all Combination Sum

You are given an array of integers candidates, which may have duplicate numbers, and a target number target. Your goal is to find all unique combinations of numbers from the array that add up to the target.

Each number from the array can only be used once in each combination. The solution should not have any duplicate combinations.

You can return the combinations in any order, and the numbers in each combination can be in any order as well.

Combination Sum II Unique

Constraints:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

Program for Printing all Combinational Sum II Solution

Recommendation for Time and Space Complexity –You should aim for a solution with O(n * (2^n)) time and O(n) space, where n is the size of the input array.

Hints for solving problems

Hint 1 :

Instead of using a hash set to remove duplicates, sort the array. Sorting helps identify and skip duplicate combinations during recursion.

Hint 2 :

Use backtracking to find combinations that sum to the target. Sorting the array lets you skip duplicate elements, ensuring unique combinations.

Hint 3 :

Recursively traverse the array from index “i”, adding elements to the combination if the sum doesn’t exceed the target. After processing an element, skip duplicates to avoid repeated combinations.

There are mainly 4 approach to solve this problem-

  1. Brute Force Method
  2. Backtracking Method
  3. Backtracking(Hash Map) Method
  4. Backtracking(Optimal) Method

1. Brute Force Method

This approach generates all possible combinations of the array and then filters out duplicates using a hash set or other data structures. While simple, it is highly inefficient due to the large number of unnecessary computations.

  • Time complexity: O(n* 2^n)
  • Space complexity: O(2^n)

Code

2. Backtracking Method

In this method, recursion is used to explore all combinations by adding elements to a current path and checking if their sum equals the target. Sorting the array beforehand helps to skip duplicate elements and ensures unique combinations.

  • Time complexity: O(n* 2^n)
  • Space complexity: O(n)

Code

3. Backtracking(Hash Map) Method

This approach uses a hash map to keep track of elements and their counts. During recursion, the hash map ensures no element is used more than its count in the array, avoiding duplicates and keeping the solution efficient.

  • Time complexity: O(n* 2^n)
  • Space complexity: O(n)

Code

4. Backtracking(Optimal) Method

This optimized approach involves sorting the array and using recursion to build combinations. Duplicate elements are skipped by comparing each element with the previous one, ensuring no duplicate combinations are generated. It is efficient in both time and space.

  • Time complexity: O(n* 2^n)
  • Space complexity: O(n)

Code

More Articles