题目描述:
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5]
and target 8
,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]
分析:
题意:给定一个候选正整型可重复数字集合,一个正整型目标值target,找到所有的组合:任意选择集合中的数字,每个位置最多一次,使得它们的和为目标值。返回所有符合条件的组合。
思路:这道题是LeetCode 39的进化版本,总体思想都是采用DFS搜索。这里主要说明几个不同点:① 每次找到一组解,都要判断跟之前的解是否重复(存在重复数字问题);② 每次搜索第k个数,不论是否把它加入sum中,接下来都从第k + 1个数开始搜索(每个位置只搜索一次)。最后返回所有不重复的解。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
vector<vector<int>> ans;
vector<int> res;
void DFS(vector<int>& candidates, int target, int sum, int n, int k){
if(target == sum){
if(find(ans.begin(), ans.end(), res) == ans.end()){
ans.push_back(res);
}
return;
}
if(k == n || sum > target){
return;
}
res.push_back(candidates[k]);
DFS(candidates, target, sum + candidates[k], n, k + 1);
res.pop_back();
DFS(candidates, target, sum, n, k + 1);
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
ans.clear();
res.clear();
int n = candidates.size();
// Exceptionl Case:
if(n == 0){
return ans;
}
// sort
sort(candidates.begin(), candidates.end());
DFS(candidates, target, 0, n, 0);
return ans;
}
};