Given an array of positive integers arr and a sum x, find all unique combinations in arr where the sum is equal to x. The same repeated number may be chosen from arr unlimited number of times. Elements in a combination (a1, a2, …, ak) must be printed in non-descending order. (ie, a1 <= a2 <= … <= ak).
The combinations themselves must be sorted in ascending order, i.e., the combination with smallest first element should be printed first. If there is no combination possible the print "Empty" (without quotes).
Input : arr = 2, 4, 6, 8 x = 8 Output : [2, 2, 2, 2] [2, 2, 4] [2, 6] [4, 4] 
Since the problem is to get all the possible results, not the best or the number of result, thus we don’t need to consider DP(dynamic programming), recursion is needed to handle it.
We should use the following algorithm.
1. Sort the array(non-decreasing). 2. First remove all the duplicates from array. 3. Then use recursion and backtracking to solve the problem. (A) If at any time sub-problem sum == 0 then add that array to the result (vector of vectors). (B) Else if sum if negative then ignore that sub-problem. (C) Else insert the present array in that index to the current vector and call the function with sum = sum-ar[index] and index = index, then pop that element from current index (backtrack) and call the function with sum = sum and index = index+1
Below is C++ implementation of above steps.
( 2 2 2 2 ) ( 2 2 4 ) ( 2 6 ) ( 4 4 ) ( 8 )
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 contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
- Program for K Most Recently Used (MRU) Apps
- Adobe Interview Experience (5 Rounds)
- Amazon Interview Experience SDE Off Campus
- Amazon Interview Experience SDE ll
- Samsung R & D internship Interview
- Print all permutations of a string in Java
- Amazon Interview Experience SDE (On Campus 2019)
- Rearrange Odd and Even values in Alternate Fashion in Ascending Order
- Print all permutation of a string using ArrayList
- Microsoft IDC Internship On-Campus Interview Experience 2018
- Recursive program to print all numbers less than N which consist of digits 1 or 3 only
- Ways to paint N paintings such that adjacent paintings don't have same colors
- K length words that can be formed from given characters without repetition
- Maximum number of 3-person teams formed from two groups