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.
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。
解集不能包含重复的组合。
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]
]
C++ ( BackTrack )
class Solution{
public:
vector<vector<int> > combinationSum(vector<int>& candidates, int target){
sort(candidates.begin(),candidates.end());
vector<vector<int> > res;
vector<int > cur;
backtrack(candidates,target,res,cur,0);
return res;
}
private:
void backtrack(vector<int>& candidates, int target, vector<vector<int> >& res,vector<int >& cur, int start){
if(target == 0){//base case
res.push_back(cur);
return;
}
//decisions
for(int i = start; i < candidates.size() && target >= candidates[i]; i++){
cur.push_back( candidates[i] );
int newtarget = target - candidates[i];
start = i;//start变成i,每次都从start开始,目的是去重
backtrack( candidates, newtarget, res, cur, start);
cur.pop_back();//回溯后没有得到正确解,回溯撤销
}
}
};
难点
去重
- 在搜索的时候,需要设置搜索起点的下标
start
,由于一个数可以使用多次,下一层的结点从这个搜索起点开始搜索; - 如果搜索起点
start
之前的数,那么因为以前的分支已经搜索过了,所以会产生重复。