-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path39. Combination Sum.cpp
More file actions
30 lines (27 loc) · 1.01 KB
/
39. Combination Sum.cpp
File metadata and controls
30 lines (27 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
void uniqueCombination(int index, int target, vector<int>& arr, vector<vector<int>>& answer, vector<int>& tempArr) {
int outOfBound = arr.size();
if (index == outOfBound) {
if (target == 0) {
answer.push_back(tempArr);
}
return;
}
// accepting the index value
if (arr[index] <= target) {
tempArr.push_back(arr[index]);
uniqueCombination(index, target - arr[index], arr, answer, tempArr);
tempArr.pop_back(); // while backtracking removing the old taken value
}
// rejecting the index value and going to the next index
uniqueCombination(index + 1, target, arr, answer, tempArr);
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> answer;
vector<int> tempArr;
uniqueCombination(0, target, candidates, answer, tempArr);
return answer;
}
};