Given an array of positive integers arr and an integer x, The task is to find all unique combinations in arr where the sum is equal to x.
The same repeated number may be chosen from arr an unlimited number of times. Elements in a combination (a1, a2, …, ak) must be printed in non-descending order. (ie, a1 <= a2 <= … <= ak). If there is no combination possible print “Empty”.
Input: arr = 2, 4, 6, 8, x = 8
[2, 2, 2, 2]
[2, 2, 4]
Recursively find all combinations and if the current combination sums up to give X then add this combination in the final set of combinations.
Follow the below steps to implement the idea:
- Sort the array arr and remove all the duplicates from the arr then create a temporary vector r. to store every combination and a vector of vector res.
- Recursively follow:
- If at any time sub-problem sum == 0 then add that array to the res (vector of vectors).
- Run a while loop till the sum – arr[I] is not negative and i is less than arr.size().
- Push arr[i] in r and recursively call for i and sum-arr[i] ,then increment i by 1.
- pop r[i] from back and backtrack.
Below is the implementation of the above approach.
( 2 2 2 2 ) ( 2 2 4 ) ( 2 6 ) ( 4 4 ) ( 8 )
Time Complexity: O(n2), where n is the size of array.
Auxiliary Space: O(n2)
This article is contributed by Aditya Nihal Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.