feat: 39_combination_sum_1
This commit is contained in:
parent
828f3e0e7b
commit
832edfa692
34
39_combination_sum_1/main.cpp
Normal file
34
39_combination_sum_1/main.cpp
Normal file
@ -0,0 +1,34 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
|
||||
sort(candidates.begin(), candidates.end());
|
||||
|
||||
vector<vector<int>> result;
|
||||
|
||||
function<void(int, vector<int>)> recursive = [&](int target, vector<int> chosen) {
|
||||
if (target < 0) return;
|
||||
|
||||
if (target == 0) {
|
||||
result.emplace_back(chosen);
|
||||
return;
|
||||
}
|
||||
|
||||
for (auto x : candidates) {
|
||||
if (chosen.size() > 0 && x > chosen.back()) {
|
||||
return;
|
||||
}
|
||||
|
||||
chosen.emplace_back(x);
|
||||
recursive(target - x, chosen);
|
||||
chosen.pop_back();
|
||||
}
|
||||
};
|
||||
|
||||
recursive(target, {});
|
||||
|
||||
return result;
|
||||
}
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user