Skip to content

Commit 92cb4cd

Browse files
committed
2
1 parent 167b122 commit 92cb4cd

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

CombinationSum/CombinationSum.cpp

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
public:
3+
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
4+
// Start typing your C/C++ solution below
5+
// DO NOT write int main() function
6+
7+
combination_set.clear();
8+
sort(candidates.begin(), candidates.end());
9+
vector<int> nums;
10+
DFS(nums, target, candidates, 0);
11+
return move(combination_set);
12+
}
13+
14+
void DFS(vector<int>& nums, int target, vector<int>& candidates, int position) {
15+
if (target < 0) return;
16+
17+
if (target == 0) {
18+
combination_set.push_back(nums);
19+
return;
20+
}
21+
22+
if (position >= candidates.size())
23+
return;
24+
25+
DFS(nums, target, candidates, position + 1);
26+
27+
int value = candidates[position];
28+
29+
for (int i = 1; i * value <= target; i++) {
30+
for (int j = 0; j < i; j++)
31+
nums.push_back(value);
32+
33+
DFS(nums, target - i * value, candidates, position + 1);
34+
35+
for (int j = 0; j < i; j++)
36+
nums.pop_back();
37+
}
38+
}
39+
40+
private:
41+
vector<vector<int>> combination_set;
42+
};

0 commit comments

Comments
 (0)