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]
题意:给定数T,在数组C中找到等于T的组合。元素可以重复利用。
思路:这题的思想和combination sum ii 基本是一样的,就是要注意的是,某一个元素本身可以重复利用,这就导致了下次深搜不是从该元素的下一个元素开始,应该是从该元素本身开始。
代码如下:
1 class Solution { 2 public: 3 vector<vector<int> > combinationSum(vector<int> &candidates, int target) 4 { 5 vector<vector<int>> res; 6 vector<int> midVal; 7 sort(candidates.begin(),candidates.end()); 8 DFS(res,midVal,candidates,target,0); 9 return res; 10 } 11 12 void DFS(vector<vector<int>> &res,vector<int> &midVal,vector<int> &candidates,int target,int start) 13 { 14 if(target<0) 15 return; 16 else if(target==0) 17 res.push_back(midVal); 18 else 19 { 20 for(int i=start;i<candidates.size();i++) 21 { 22 23 midVal.push_back(candidates[i]); 24 DFS(res,midVal,candidates,target-candidates[i],i); // i 25 midVal.pop_back(); 26 } 27 } 28 } 29 };