题目
给定一个数组 candidates
和一个目标数 target
,找出 candidates
中所有可以使数字和为 target
的组合。
candidates
中的每个数字在每个组合中只能使用一次。
说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
解答
class Solution {
public:
bool Recur(vector<vector<int> > & result, vector<int> & temp_arr, const vector<int> & candidates, int start, int target) {
if (target < 0)
return false;
else if (target == 0) {
result.push_back(temp_arr);
return false;
}
else {
for (int i = start; i < candidates.size(); i++) {
if (i > start && candidates[i] == candidates[i-1]) continue; // 防止重复序列
temp_arr.push_back(candidates[i]);
bool flag = Recur(result, temp_arr, candidates, i+1, target-candidates[i]);
temp_arr.pop_back();
if (!flag)
break;
}
return true;
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int> > result;
vector<int> temp_arr;
Recur(result, temp_arr, candidates, 0, target);
return result;
}
};