Simple C++ Recursive Approach with //Comments


#1

Comment body goes here.

void combinations(vector<vector>&ans,vector&temp,vector&A,int i,int t){

if(t==0){// the target is found
    ans.push_back(temp);
    return;
}
if(t<0){
    return;
}
for(int j=i;j<A.size();j++){
    temp.push_back(A[j]);
    combinations(ans,temp,A,j,t-A[j]);//Passing index same as j(not j++) as repetition of same no is allowed and now updating the current target
    temp.pop_back();
    
}
return;

}

vector<vector > Solution::combinationSum(vector &A, int B) {
sort(A.begin(),A.end());
int x=A.size()-1;
//Removing duplicates as repetition is allowed
while(x>0)
{
if(A[x]==A[x-1]) A.erase(A.begin()+x); x–;
}
vector<vector>ans;
vectortemp;
combinations(ans,temp,A,0,B);
return ans;

}