LeetCode Combination Sum

LeetCode Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

• All numbers (including target) will be positive integers.
• The solution set must not contain duplicate combinations.

For example, given candidate set `[2, 3, 6, 7]` and target `7`,
A solution set is:

```[
[7],
[2, 2, 3]
]```

```class Solution {
public:
void work(set<vector<int>>& ans, vector<int>& candidates, vector<int>& sol, int target) {
if (target == 0) {
vector<int> tmp = sol;
sort(tmp.begin(), tmp.end());
ans.insert(tmp);
}
else {
for (int i = 0; i < candidates.size(); i++) {
if (candidates[i] > target)break;
sol.push_back(candidates[i]);
work(ans, candidates, sol, target - candidates[i]);
sol.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
set<vector<int>> ans;
vector<int> sol;
sort(candidates.begin(), candidates.end());
work(ans, candidates, sol, target);
return vector<vector<int>>(ans.begin(), ans.end());
}
};
```

```class Solution {
public:
void work(vector<vector<int>>& ans, vector<int>& candidates, vector<int>& sol, int target) {
if (target == 0) {
ans.push_back(sol);
}
else {
for (int i = 0; i < candidates.size(); i++) {
if (candidates[i] > target || (sol.size() > 0 && candidates[i] < sol[sol.size() - 1]))continue;
sol.push_back(candidates[i]);
work(ans, candidates, sol, target - candidates[i]);
sol.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> sol;
sort(candidates.begin(), candidates.end());
work(ans, candidates, sol, target);
return ans;
}
};
```

```class Solution {
public:
void work(vector<vector<int>>& ans, vector<int>& candidates, int idx, vector<int>& sol, int target) {
if (target == 0) {
ans.push_back(sol);
}
else {
for (int i = idx; i < candidates.size(); i++) {
if (candidates[i] > target)break;
sol.push_back(candidates[i]);
work(ans, candidates, i, sol, target - candidates[i]);
sol.pop_back();
}
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> ans;
vector<int> sol;
sort(candidates.begin(), candidates.end());
work(ans, candidates, 0, sol, target);
return ans;
}
};
```