题意
- 给一个数组和target, 找出数组中所有和为target的组合
方法
- DFS
代码
class Solution {
private:
vector<vector<int>> res;
vector<int> tmp;
public:
int getNextNumberIndex(vector<int>& candidates, int i) //寻找下一个不同元素的下标
{
int next = i;
while (next < candidates.size() && candidates[next] == candidates[i])
{
++ next;
}
return next;
}
void dfs(vector<int>& candidates, int i, int target) //i为当前元素的下标
{
if (target == 0)
{
res.push_back(tmp);
}
else if (target > 0 && i < candidates.size())
{
tmp.push_back(candidates[i]); //选择当前元素
dfs(candidates, i + 1, target - candidates[i]);
tmp.pop_back(); //不选当前元素,选择下一个不同元素
dfs(candidates, getNextNumberIndex(candidates, i), target);
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end()); //首先排序
dfs(candidates, 0, target);
return res;
}
};
标签:tmp,target,int,next,II,vector,candidates,LeetCode40,总和
From: https://www.cnblogs.com/Figure_at_a_Window/p/16866997.html