/*
39. Combination Sum My Submissions QuestionEditorial Solution
Total Accepted: 88140 Total Submissions: 286018 Difficulty: Medium
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.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
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]
*/
/*
解题思路:
深度遍历的典型题目,可以重复使用同一个元素,所以每次往下层递归的时候游标并不+1,还是i.
注意事项:
首先要对数组进行排序,只有这样才能保证结果都是有序的
防止重复,暂时的结果先放在一个set中
*/
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
//本题属于深度遍历
if(candidates.size()==0)return {};
set<vector<int>> _set;
vector<int> out;
sort(candidates.begin(),candidates.end());
dfs(candidates,0,target,out,_set);
return vector<vector<int>> (_set.begin(),_set.end());
}
void dfs(vector<int>& candidates,int start,int target,vector<int>&out,set<vector<int>>&_set){
if(target==0){
_set.insert(out);
return ;
}
if(target<0)return ;
for(int i=start;i<candidates.size();i++){
out.push_back(candidates[i]);
dfs(candidates,i,target-out.back(),out,_set);
out.pop_back();
}
}
};