|
| 1 | +#include<iostream> |
| 2 | +#include<vector> |
| 3 | +#include<set> |
| 4 | +#include<algorithm> |
| 5 | +using namespace std; |
| 6 | +class Solution { |
| 7 | +public: |
| 8 | + set<vector<int>> st; |
| 9 | + void solve(vector<int>& input, int target, vector<int>& current, int sum) { |
| 10 | + if (sum == target) { |
| 11 | + st.insert(current); |
| 12 | + return; |
| 13 | + } |
| 14 | + if (sum > target || input.empty()) { |
| 15 | + return; |
| 16 | + } |
| 17 | + int curr = input[0]; |
| 18 | + // skipInput: skip current element |
| 19 | + vector<int> skipInput(input.begin() + 1, input.end()); |
| 20 | + while (!skipInput.empty() && skipInput[0] == curr) { |
| 21 | + skipInput.erase(skipInput.begin()); |
| 22 | + } |
| 23 | + solve(skipInput, target, current, sum); |
| 24 | + // takeInput: take current element |
| 25 | + vector<int> takeInput(input.begin() + 1, input.end()); |
| 26 | + current.push_back(curr); |
| 27 | + solve(takeInput, target, current, sum + curr); |
| 28 | + current.pop_back(); // backtrack |
| 29 | + } |
| 30 | + vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { |
| 31 | + sort(candidates.begin(), candidates.end()); |
| 32 | + vector<int> current; |
| 33 | + solve(candidates, target, current, 0); |
| 34 | + return vector<vector<int>>(st.begin(), st.end()); |
| 35 | + } |
| 36 | +}; |
| 37 | +int main(){ |
| 38 | + Solution sol; |
| 39 | + vector<int> candidates = {10, 1, 2, 7, 6, 1, 5}; |
| 40 | + int target = 8; |
| 41 | + vector<vector<int>> result = sol.combinationSum2(candidates, target); |
| 42 | + cout << "Combinations that sum to " << target << ":" << endl; |
| 43 | + for (const auto& combo : result) { |
| 44 | + cout << "["; |
| 45 | + for (size_t i = 0; i < combo.size(); ++i) { |
| 46 | + cout << combo[i]; |
| 47 | + if (i < combo.size() - 1) { |
| 48 | + cout << ","; |
| 49 | + } |
| 50 | + } |
| 51 | + cout << "]" << endl; |
| 52 | + } |
| 53 | + return 0; |
| 54 | +} |
0 commit comments