题目描述:
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数,搜索所有和为target数的组合。和上一题不同:本题的每个数字不能无限重复使用。
解题思路:
这题我的解法还是和上一题相同,只不过这题有重复的数字而且每个数字还不能重复使用,所以要稍微变动下代码。
- 上一层给下一层的index要+1;
- 要消除重复的数字:先排序再检验
代码:
1 class Solution { 2 public: 3 vector<vector<int>> res; 4 void selectAll(vector<int>& candidates, int target, int index, vector<int> nums){ 5 //candidates、target为题目给的字符串和目标数,index为上一层nums添加的数字在candidates中的位置,nums为最后要添加的一维数组 6 if(target == 0) 7 res.push_back(nums); 8 else if(target > 0){ 9 int n = candidates.size(); 10 for(int i = index; i < n; i++){ 11 //每层每种情况的遍历 12 if(i>index && candidates[i]==candidates[i-1]) 13 //检验重复 14 continue; 15 vector<int> t(nums); 16 t.push_back(candidates[i]); 17 selectAll(candidates, target-candidates[i], i+1, t);//让i+1不能重复使用数字 18 } 19 } 20 } 21 vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { 22 sort(candidates.begin(),candidates.end()); 23 vector<int> nums; 24 selectAll(candidates, target, 0, nums); 25 return res; 26 } 27 };