Given a set of candidate numbers (
candidates
) (without duplicates) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
The same repeated number may be chosen from
candidates
unlimited number of times.
Note:
- All numbers (including
target
) will be positive integers. - The solution set must not contain duplicate combinations.
Example 1:
Input: candidates =[2,3,6,7],
target =7
, A solution set is: [ [7], [2,2,3] ]
Example 2:
Input: candidates = [2,3,5],
target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
================ Recursive ================
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
set<vector<int>> sol;
vector<int> ans;
int sum = 0;
helper(candidates, target, sum, ans, sol);
vector<vector<int>> sol_return(sol.begin(), sol.end());
return sol_return;
}
void helper(vector<int>& candidates, int target, int sum, vector<int> ans,
set<vector<int>>& sol) {
if (sum > target) {
return;
}
if (sum == target) {
sort(ans.begin(), ans.end());
sol.insert(ans);
return;
}
for (int num : candidates) {
if (sum + num <= target) {
ans.push_back(num);
sum += num;
helper(candidates, target, sum, ans, sol);
sum -= num;
ans.pop_back();
}
}
return;
}
};
=========== efficient one ========
class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int>> ans; vector<int> vec; sort(candidates.begin(), candidates.end()); heleper(candidates, ans, vec, 0, target); return ans; } void heleper(vector<int> candidates, vector<vector<int>> &ans, vector<int> &vec, int start, int target) { if (target == 0) { ans.push_back(vec); return; } for (int i = start; i < candidates.size() && target - candidates[i] >= 0; i++) { vec.push_back(candidates[i]); heleper(candidates, ans, vec, i, target - candidates[i]); vec.pop_back(); } } };
No comments:
Post a Comment