Very clean, optimized and easy to understand code


#1

void combinationSumUtil(vector &A, int idx, int t, vector<vector>& res, vector& local) {
if ((t < 0) || (idx >= A.size())) {
return;
}

if ((t == 0) || ((idx >= A.size()) && (t == 0))) {
    res.push_back(local);
    return;
}

local.push_back(A[idx]);
combinationSumUtil(A, idx, t-A[idx], res, local);
local.pop_back();
combinationSumUtil(A, idx+1, t, res, local);

}

vector<vector > Solution::combinationSum(vector &A, int B) {
vector<vector> res;
vector local;
vector::iterator ip;
sort(A.begin(), A.end());
// Using std::unique
ip = std::unique(A.begin(), A.end());
// Resizing the vector so as to remove the undefined terms
A.resize(std::distance(A.begin(), ip));

combinationSumUtil(A, 0, B, res, local);
return res;

}