|
| 1 | +## 组合总和2 |
| 2 | + |
| 3 | +### 题目描述 |
| 4 | + |
| 5 | +给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 |
| 6 | + |
| 7 | +candidates 中的每个数字在每个组合中只能使用一次。 |
| 8 | + |
| 9 | +说明: |
| 10 | + |
| 11 | +所有数字(包括目标数)都是正整数。 |
| 12 | +解集不能包含重复的组合。 |
| 13 | + |
| 14 | +``` |
| 15 | +示例 1: |
| 16 | +输入: candidates = [10,1,2,7,6,1,5], target = 8, |
| 17 | +所求解集为: |
| 18 | +[ |
| 19 | + [1, 7], |
| 20 | + [1, 2, 5], |
| 21 | + [2, 6], |
| 22 | + [1, 1, 6] |
| 23 | +] |
| 24 | +
|
| 25 | +示例 2: |
| 26 | +输入: candidates = [2,5,2,1,2], target = 5, |
| 27 | +所求解集为: |
| 28 | +[ |
| 29 | + [1,2,2], |
| 30 | + [5] |
| 31 | +] |
| 32 | +``` |
| 33 | + |
| 34 | +### 思路 |
| 35 | + |
| 36 | +和39题一模一样,注意他有重复数,需要去除重复的结果. |
| 37 | + |
| 38 | +还要注意回溯是往后回溯,不是原地回溯了 |
| 39 | + |
| 40 | +```CPP |
| 41 | +class Solution { |
| 42 | +public: |
| 43 | + vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { |
| 44 | + vector<vector<int>> ans; |
| 45 | + vector<int> tmp; |
| 46 | + sort(candidates.begin(),candidates.end()); |
| 47 | + int len = candidates.size(); |
| 48 | + |
| 49 | + dfs(ans,tmp,candidates,target,len,0); |
| 50 | + |
| 51 | + return ans; |
| 52 | + } |
| 53 | + |
| 54 | + void dfs(vector<vector<int>> &ans,vector<int> &tmp,vector<int> &nums,int target,int len,int index) { |
| 55 | + |
| 56 | + if(target == 0){ |
| 57 | + auto iter = find(ans.begin(),ans.end(),tmp); |
| 58 | + if(iter == ans.end())ans.push_back(tmp); |
| 59 | + } |
| 60 | + |
| 61 | + for(int i = index;i<len && target >= nums[i];i++){ |
| 62 | + tmp.push_back(nums[i]); |
| 63 | + dfs(ans,tmp,nums,target - nums[i],len,i+1);//注意i+1 |
| 64 | + tmp.pop_back(); |
| 65 | + } |
| 66 | + } |
| 67 | +}; |
| 68 | +``` |
0 commit comments