VOOZH about

URL: https://www.geeksforgeeks.org/dsa/all-unique-combinations-whose-sum-equals-to-k/

⇱ All Unique Subsets Equals to Target - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

All Unique Subsets Equals to Target

Last Updated : 26 Sep, 2025

Given an array arr[] of integers and an integer target, find all unique combinations of elements where the sum of the chosen elements is equal to target.

Note: Each element in the array can be used at most once in the combination.

Examples:

Input: arr[] = [1, 2, 3], target = 5
Output: [[2, 3]]
Explanation: There is only one unique combinations whose sum is equal to the target.

Input: arr[] = [1, 3, 2, 2, 2], target = 4
Output: [[1, 3], [2, 2]]
Explanation: There are two unique possible combinations whose sum is equal to target.

[Approach] Using Recursion and Backtracking

The idea is to sort the array and explore all possible combinations of numbers that add up to the target. For each element, we reduce the target by its value and continue the process recursively. If at any point the target becomes zero, it means we have found a valid combination. On the other hand, if the target goes negative, we backtrack and discard that path.

Pseudo-code Idea

Base cases:

  • If target < 0 : not a valid combination, so return back.
  • If target == 0 : valid combination, so store it as an answer.

Recursive choices:
At each step, we have two options:

  • Pick the current element, reduce the target by arr[i] and call recursion with (i+1, target - arr[i]). Increment in index (i+1) because each element can only be used once.
  • Skip the current element, move to the next index (i+1, target) but also skip all duplicates of the current element to avoid repeating the same combination.

Why do we sort the array?
We sort the array to avoid duplicate combinations.
Example: arr[] = [1, 2, 3, 2], target = 5

  • Without sorting, possible combinations might look like: [1, 2, 2], [2, 3], [3, 2]
  • After sorting (arr[] = [1, 2, 2, 3]), the combinations become: [1, 2, 2], [2, 3]

Now duplicates like [3,2] are automatically avoided.


Output
1 3 
2 2 

Time Complexity: O(n*2n), where 2n comes from generating all subsets and n from copying/traversing elements in each subset.
Auxiliary Space: O(n)

Comment
Article Tags: