![]() |
VOOZH | about |
Given an array arr[] of distinct integers and an integer target, find all unique combinations of array where the sum of chosen element is equal to target. The same element may be chosen any number of times to make target.
Examples:
Input: arr[] = [1, 2, 3], target = 5
Output: [[1, 1, 1, 1, 1], [1, 1, 1, 2], [1, 1, 3], [1, 2, 2], [2, 3]]
Explanation: All the combination have sum of elements equals to target.Input: arr[] = [2, 4], target = 1
Output: []
Explanation: No combination exits whose sum is equals to target
The idea is to 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. This way, recursion combined with backtracking helps us systematically generate all valid combinations without missing any possibilities.
Base cases:
Recursive choices:
At each step, we have two options:
1 1 1 1 1 1 1 1 2 1 1 3 1 2 2 2 3
Time Complexity: O(n^(T/M)), where n is the number of candidates, T is the target, and M is the smallest candidate.
Backtracking can be visualized as a DFS on an n-ary tree:
Auxiliary Space: O(T / M), because the recursion stack can go as deep as the maximum number of elements in a combination (adding the smallest candidate repeatedly).