Combination Sum | Practice | GeeksforGeeks

Given an array of integers and a sum B, find all unique combinations in the array where the sum is equal to B. The same number may be chosen from the array any number of times to make B.
Note:
        1. All numbers will be positive integers.
        2. Elements in a combination (a1, a2, ..., ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ ... ≤ ak).
        3. The combinations themselves must be sorted in ascending order.

Example 1:
Input:
N = 4
arr[] = {7,2,6,5}
B = 16
Output:
(2 2 2 2 2 2 2 2)
(2 2 2 2 2 6)
(2 2 2 5 5)
(2 2 5 7)
(2 2 6 6)
(2 7 7)
(5 5 6)

Example 2:
Input:
N = 11
arr[] = {6,5,7,1,8,2,9,9,7,7,9}
B = 6
Output:
(1 1 1 1 1 1)
(1 1 1 1 2)
(1 1 2 2)
(1 5)
(2 2 2)
(6)


Your Task:
Your task is to complete the function combinationSum() which takes the array A and a sum B as inputs and returns a list of list denoting the required combinations in the order specified in the problem description. The printing is done by the driver's code. If no set can be formed with the given set, then  "Empty" (without quotes) is printed.

Expected Time Complexity: O(X2 * 2N), where X is average of summation B/arri for every number in the array.
Expected Auxiliary Space: O(X * 2N)

Constraints:
1 <= N <= 30
1 <= A[i] <= 20
1 <= B <= 100
0
sandeep552112 hours ago
C++ Easy to understand Solution
void comb2(vector<int> &A,vector<int> &v,vector<vector<int>> &ans,int i,int n,int tar) // 0ms Accepted Solution by backtracking
   {
       if(!tar) // base case
       {
           ans.push_back(v);
           return;
       }
       if(i==n or tar<0) // base case
           return;
       unordered_map<int,int> mp;
       for (int j = i; j < n; j++)
       {
           if(mp.find(A[j])!=mp.end()) // for eleminating duplicates
               continue;
           v.push_back(A[j]);
           mp[A[j]]++; // visited
           comb2(A,v,ans,j,n,tar-A[j]);
           v.pop_back(); // backtrack..
       }
   }
   vector<vector<int> > combinationSum(vector<int> &s, int tar) {
       // Your code here
       vector<vector<int>> ans;
       vector<int> v;
       sort(s.begin(),s.end()); // game changer statement...
       comb2(s,v,ans,0,s.size(),tar);
       return ans;
   }
+1
milindprajapatmst1916 hours ago
Total Time Taken: 0.43/5.08
 
class Solution {
  public:
    vector<vector<int>> result;
    void help(int index, vector<int>& A, int B, vector<int>& p) {
        if (B < 0)
            return;
        if (index == A.size()) {
            if (B == 0)
                result.push_back(p);
            return;
        }
        p.push_back(A[index]);
        help(index, A, B - A[index], p);
        p.pop_back();
        help(index + 1, A, B, p);
    }
    
    vector<vector<int>> combinationSum(vector<int> &A, int B) {
        sort(A.begin(), A.end());
        A.erase(unique(A.begin(), A.end()), A.end());
        vector<int> p;
        help(0, A, B, p);
        return result;
    }
};

0
2019uec10491 day ago
what is wrong with this??
 
class Solution { public: void combi(int i,int B, vector<int> &ds, vector<vector<int>> &ans ,vector<int> &A) {     if(i==A.size())     {         if(B==0)         {          sort(ds.begin(),ds.end());          ans.push_back(ds);            }         return;     }     if(A[i]<=B)     {         ds.push_back(A[i]);         combi(i,B-A[i],ds, ans ,A);         ds.pop_back();     }     combi(i+1,B,ds,ans ,A);      } public:   //Function to return a list of indexes denoting the required    //combinations whose sum is equal to given number.   vector<vector<int> > combinationSum(vector<int> &A, int B )   {         vector<vector<int>> ans;   vector<int> ds;   combi(0,B,ds,ans,A);   return ans;              // Your code here            }
0
sakesai301 week ago
class Solution{   //Function to return a list of indexes denoting the required    //combinations whose sum is equal to given number.   static ArrayList<ArrayList<Integer>> combinationSum(ArrayList<Integer> A, int B)   {      ArrayList<ArrayList<Integer>> ans  = new ArrayList<ArrayList<Integer>>();       ArrayList<Integer> stack = new ArrayList<>();       int n = A.size();       Collections.sort(A);       subSequenceWithoutOrder(0,B,stack,A,n,ans);              return ans;          }      public static void subSequenceWithoutOrder(int index,int target,ArrayList<Integer> stack,ArrayList<Integer> arr,int n,ArrayList<ArrayList<Integer>> list) {     if(target == 0){         list.add(new ArrayList(stack));         return;     } for(int i = index;i<n;i++){     if(i>index && arr.get(i)==arr.get(i-1)) continue;     if(arr.get(i)>target) break;  stack.add(arr.get(i));  subSequenceWithoutOrder(i, target-arr.get(i), stack, arr,n,list);  stack.remove(stack.size()-1); } }}
0
sourabhgharad19062 weeks ago
 public static void combinations(int i,int target,ArrayList<Integer> A,ArrayList<ArrayList<Integer>> list,ArrayList<Integer> l){       if(i == A.size()){           if(target == 0){               // Collections.sort(l);               list.add(new ArrayList<>(l));               // System.out.print(l);           }           return ;       }       if(target >= A.get(i))       {           l.add(A.get(i));           target -= A.get(i);           combinations(i,target,A,list,l);           target += A.get(i);           l.remove(new Integer(A.get(i)));       }       combinations(i+1,target,A,list,l);   }   static ArrayList<ArrayList<Integer>> combinationSum(ArrayList<Integer> A, int B)   {       ArrayList<ArrayList<Integer> > list = new ArrayList<>();       ArrayList<Integer> l = new ArrayList<>();       Set<Integer> set = new HashSet<>(A);       A.clear();       A.addAll(set);       Collections.sort(A);       combinations(0,B,A,list,l);       return list;   }
 
0
rajbhargavp3 weeks ago
// { Driver Code Starts//Initial template for C++
#include <bits/stdc++.h>using namespace std;
// } Driver Code Ends//User function template for C++
class Solution { public:   //Function to return a list of indexes denoting the required    //combinations whose sum is equal to given number.   vector<vector<int> >ans;   void util(vector<int> &arr,int &sum,int i,int currsum,vector<int> &currnum){       if(currsum>sum || i==arr.size()){           return;       }       if(currsum==sum){           ans.push_back(currnum);       }       currnum.push_back(arr[i]);       util(arr,sum,i,currsum+arr[i],currnum);       currnum.pop_back();       util(arr,sum,i+1,currsum,currnum);          }   vector<vector<int> > combinationSum(vector<int> &A, int B) {       // Your code here       sort(A.begin(),A.end());       A.erase(unique(A.begin(),A.end()),A.end());       vector<int> currnum;       util(A,B,0,0,currnum);       ans.erase(unique(ans.begin(),ans.end()),ans.end());       return ans;   }};
// { Driver Code Starts.int main(){   int t;   cin>>t;   while(t--){       int n;       cin>>n;       vector<int> A;       for(int i=0;i<n;i++){           int x;           cin>>x;           A.push_back(x);       }          int sum;       cin>>sum;       Solution ob;       vector<vector<int>> result = ob.combinationSum(A, sum);    if(result.size()==0){     cout<<"Empty";    }       for(int i=0;i<result.size();i++){           cout<<'(';           for(int j=0;j<result[i].size();j++){               cout<<result[i][j];               if(j<result[i].size()-1)                   cout<<" ";           }           cout<<")";       }       cout<<"\n";   }}   // } Driver Code Ends
+1
bhaskarmaheshwari83 weeks ago
 
 
 
 
 
 
 
 void Knapsack(vector<int>& a,int sum,int n, vector<vector<int> > &ans,vector<int> op)   {       if(n==0||sum<0)       return;       if(sum==0)       {           //sort(op.begin(),op.end());           ans.push_back(op);           return;       }                     if(a[n-1]<=sum)//imp not sum<=arr[n-1]      {          vector<int>op1=op;          vector<int>op2=op;          op1.push_back(a[n-1]);           Knapsack(a,sum-a[n-1],n,ans,op1);                        Knapsack(a,sum,n-1,ans,op2);      }      else      Knapsack(a,sum,n-1,ans,op);   }   vector<vector<int> > combinationSum(vector<int> &A, int B) {       // Your code here         vector<vector<int> > ans;         vector<int>op;         sort(A.begin(), A.end(),greater<int>());       A.erase(unique(A.begin(), A.end()), A.end());       //unique duplicates remove kr deta hain and iterator is  on next element of last element not remove in array       Knapsack(A,B,A.size(),ans,op);                sort(ans.begin(),ans.end());       return ans;   }
0
bhaskarmaheshwari8
This comment was deleted.
+1
abhiswc291 month ago
Basic Approach using Recursion - python 3
class Solution:
    def combinationalSum(self,A, B):
        def recursion(index,arr,target,ds=[]):
            if index==len(arr):
                if target==0:
                    ans.append(ds.copy())
                return
            if arr[index]<=target:
                ds.append(arr[index])
                recursion(index,arr,target-arr[index],ds)
                ds.pop()
            recursion(index+1,arr,target,ds)
        
        ans=list()
        A=list(set(A))
        A.sort()
        recursion(0,A,B)
        return ans
0
aric_ash1 month ago
EASY C++ SOLUTION:
 
void solve(int j, int sum, vector<int> temp, vector<vector<int> > &ans, vector<int> &A){       if(sum==0){           ans.push_back(temp);       }       if(sum<0){           return;       }       for(int i=j;i<A.size();i++){           if(sum-A[i]>=0){               j=i;               temp.push_back(A[i]);               solve(j,sum-A[i], temp, ans, A);               temp.pop_back();           }       }   }      vector<vector<int> > combinationSum(vector<int> &A, int B) {       // Your code here       vector<vector<int> > ans;       sort(A.begin(), A.end());       A.erase(unique(A.begin(), A.end()), A.end());       vector<int> temp;       solve(0, B, temp, ans, A);       sort(ans.begin(), ans.end());       return ans;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.