题目描述
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.
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]
]
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
dfs解题思路
- 考察深度优先搜索
dfs版本
class Solution {
public:
vector<vector<int>> res;
vector<int> path;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
dfs(candidates, 0, target);
return res;
}
void dfs(vector<int>& candidates, int level, int cur){
if(cur == 0){
res.push_back(path);
return;
}
for(int i = level; i < candidates.size(); i++){
if(candidates[i] > cur){
break;
}
path.push_back(candidates[i]);
dfs(candidates, i, cur - candidates[i]);
path.pop_back();
}
}
};
C++代码
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int> > res;
vector<int> cur;
sort(candidates.begin(), candidates.end());
dfs(candidates, target, 0, cur, res);
return res;
}
private:
void dfs(vector<int>& candidates, int target, int start, vector<int>& cur, vector<vector<int> > &res){
if(target == 0){
res.push_back(cur);
return;
}
for(int i = start; i < candidates.size(); i++){
if(candidates[i] > target){
break;
}
cur.push_back(candidates[i]);
// 这里i其实是被复用
// 下一层还是以i来进行判断
dfs(candidates, target - candidates[i], i, cur, res);
cur.pop_back();
}
}
};
200207dfs解题思路
- 考察深度优先搜索
- 给出一个target ,每次选中一个元素的时候,就将目标值与选中元素的值进行想减,如果减到0,证明得出一个结果
- 需要有一个索引,这样从最底层的时候,便于知道 此时搜到第多少个元素了
C++代码
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> cur;
sort(candidates.begin(), candidates.end()); // 这里之所以要进行排个序,是为了让下面做剪枝,防止报栈溢出
dfs(candidates, target, res, cur, 0);
return res;
}
void dfs(vector<int>& candidates, int target, vector<vector<int>>& res, vector<int>& cur, int start){
if(target == 0){
res.push_back(cur);
return;
}
for(int i = start; i < candidates.size(); i++){
if(candidates[i] > target){
return;
}
cur.push_back(candidates[i]);
dfs(candidates, target - candidates[i], res, cur, i); // i 表示很重要,想象一下,栈从最底层向上返回的时候,当前元素不满足的话,肯定要记住上层遍历到哪了
cur.pop_back();
}
}
};