![]() |
VOOZH | about |
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.
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.
Base cases:
Recursive choices:
At each step, we have two options:
Why do we sort the array?
We sort the array to avoid duplicate combinations.
Example: arr[] = [1, 2, 3, 2], target = 5
Now duplicates like [3,2] are automatically avoided.
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)