Difference in solutions


#1

hi so I wrote the code something like this and it worked

typedef vector<int> veci;
void com(veci &A,vector<veci>&res,veci &c,int B,int sum,int j){
            if(sum>B)
                return;

    if(B==sum){
        res.push_back(c);
        return;
    }
    for(int i=j;i<A.size();i++){
        sum+=A[i];
        c.push_back(A[i]);
        com(A,res,c,B,sum,i);
        sum-=A[i];
        c.pop_back();
    }
}

vector<vector<int> > Solution::combinationSum(vector<int> &A, int B) {
    vector<veci> res;
    veci c;
    unordered_set<int>s(A.begin(),A.end());
    A.assign(s.begin(),s.end());
    sort(A.begin(),A.end());
    com(A,res,c,B,0,0);
    return res;
}

initially, I wrote this and I didn’t get accepted but I don’t think there’s any change in logic can some help me find the difference

typedef vector<int> veci;
void com(veci &A,vector<veci>&res,veci &c,int B,int sum,int j){
 
    if(B==sum){
        res.push_back(c);
        return;
    }
    for(int i=j;i<A.size();i++){
        sum+=A[i];
        c.push_back(A[i]);
       if(sum<=B)
             com(A,res,c,B,sum,i);
        else{
         sum-=A[i];
         c.pop_back();
         return ;
       }
    }
}

vector<vector<int> > Solution::combinationSum(vector<int> &A, int B) {
    vector<veci> res;
    veci c;
    unordered_set<int>s(A.begin(),A.end());
    A.assign(s.begin(),s.end());
    sort(A.begin(),A.end());
    com(A,res,c,B,0,0);
    return res;
}