题目描述
给定一个候选人编号的集合 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的每个数字在每个组合中只能使用 一次 。
**注意:**解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]
提示:
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
解答
cpp
class Solution {
public:
vector<vector<int>> res;
vector<int> path; // 记录当前路径
void backtrack(vector<int>& candidates, int beg, int target, vector<bool> &used)
{
if(target == 0) // 找到一个结果
{
res.push_back(path);
return;
}
//
for(int i = beg; i < candidates.size() && candidates[i] <= target; ++ i)
{
// 同一层使用过相同元素就跳过
if(i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) continue;
path.push_back(candidates[i]);
used[i] = true;
backtrack(candidates, i + 1, target - candidates[i],used);
used[i] = false;
path.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
// 一个路径中的某一位置不可以用重复的元素,这样会造成结果重复
// 使用used数组标识是同一层用过某个节点还是同一个枝干用过某个节点
// candidates[i] == candidates[i - 1] && used[i - 1] == false 表示的是同一层使用过,也就是路径上某一位置之间已经用过candidates[i - 1]元素
// 先升序排序
vector<bool> used(candidates.size(), false);
path.clear();
res.clear();
sort(candidates.begin(), candidates.end());
backtrack(candidates, 0, target, used);
return res;
}
};