[InterviewBit] Combination Sum

Combination Sum

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
void helper(vector<int>& A, vector<vector<int>>& res, vector<int> now, int rem, int p) {
if(rem == 0) res.push_back(now);
else if(rem < 0 or p == A.size()) return;
else {
for(int i = 0; i * A[p] <= rem; i++) {
if(i) now.push_back(A[p]);
helper(A,res,now,rem-i*A[p],p+1);
}
}
}
vector<vector<int>> Solution::combinationSum(vector<int> &A, int B) {
vector<vector<int>> res;
sort(begin(A), end(A));
A.erase(unique(begin(A), end(A)), end(A));
helper(A, res, vector<int>() = {}, B, 0);
sort(begin(res),end(res));
return res;
}


Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/22/PS/interviewbit/combination-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.