题目描述
- 题目中所有的数字(包括目标数T)都是正整数
- 你给出的组合中的数字 (a 1, a 2, … , a k) 要按非递增排序 (ie, a 1 ≤ a 2 ≤ … ≤ a k).
- 结解集中不能包含重复的组合
[2, 2, 3]
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 (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1 ≤ a 2 ≤ … ≤ a k).
- The solution set must not contain duplicate combinations.
For example, given candidate set2,3,6,7and target7,
A solution set is:
[7]
[2, 2, 3]
class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
vector <vector<int>>res;
vector<int> temp;
sort(candidates.begin(),candidates.end());
Sum(res,temp,candidates,0,target);
return res;
}
void Sum(vector <vector <int>> &res,vector<int> &temp,vector<int >&candidates,int k,int target){
if (target==0){
res.push_back(temp);
return ;
}
if (target <0 || k>=candidates.size())
return ;
vector<int> t =temp;
temp.push_back(candidates[k]);
Sum(res,temp,candidates,k,target-candidates[k]);
Sum(res,t,candidates,k+1,target);
}
};