排列组合类的题目是DFS的一个比较经典的案例。
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.
题目中给出candidate number是没有重复的,并且和target一样均为正数。同时规定,同一个数可以不限次数重复使用。
方法:DFS+剪枝(排序,修剪掉sum已经大于target的分支)
code:
class Solution {
public:
vector<vector<int>> solutions;
vector<int> result;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
dfs(0, candidates, target);
return solutions;
}
void dfs(int level, vector<int>& candidates, int target) {
if(target == 0) {
solutions.push_back(result);
return;
} else if(target < 0) return;
for(int i = 0; i < candidates.size(); i++) {
if(result.size()> 0 && candidates[i] < result[result.size()-1]) continue; //因为candidates中没有重复的元素,可以直接这样限定
result.push_back(candidates[i]);
dfs(level+1, candidates, target - candidates[i]);
result.pop_back();
}
}
};


373

被折叠的 条评论
为什么被折叠?



