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

same repeated number may be chosen from C

Note:

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

​[2, 3, 6, 7]​​ and target ​​7​​, 

A solution set is: 


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



class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int>tmp;
dfs(candidates, target, tmp, 0);
return s;
}
private:

void dfs(vector<int>& candidates, int target, vector<int>&tmp,int cur){
if (target < 0) return;
if (target==0){
s.push_back(tmp);
return;
}
for (int i = cur; i < candidates.size(); i++){
tmp.push_back(candidates[i]);
dfs(candidates, target-candidates[i], tmp,i);//i,因为一个数字可以出现多次
tmp.pop_back();
}
}

vector<vector<int> > s;
};


class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<int>tmp;
dfs(candidates, target, tmp, 0);
return s;
}
private:

void dfs(vector<int>& candidates, int target, vector<int>&tmp,int cur){
if (target < 0) return;
if (target==0){
s.push_back(tmp);
return;
}
for (int i = cur; i < candidates.size(); i++){
if (cur != i&&candidates[i] == candidates[i-1]) continue;
tmp.push_back(candidates[i]);
dfs(candidates, target-candidates[i], tmp,i);
tmp.pop_back();
}
}

vector<vector<int> > s;
};