LeetCode40 Combination Sum II
题目:
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. (Medium)
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] ]
分析:
主体回溯框架和Combination Sum I一致,不同之处在于一个元素不能重复用,同时不能出现重复的组合。
所以DFS那一个条件 start 变为start + 1;
同时插入result之前判定是否出现过重复的结果。
代码:
1 class Solution { 2 private: 3 vector<vector<int>>result; 4 void dfs(int start, int end, const vector<int>& candidates, int target, vector<int>& internal) { 5 if (start > end) { 6 return; 7 } 8 if (candidates[start] == target) { 9 internal.push_back(candidates[start]); 10 if ( find(result.begin(), result.end(), internal) == result.end()) { 11 result.push_back(internal); 12 } 13 internal.pop_back(); 14 return; 15 } 16 if (candidates[start] > target) { 17 return; 18 } 19 dfs(start + 1, end, candidates, target, internal); 20 internal.push_back(candidates[start]); 21 dfs(start + 1, end, candidates, target - candidates[start], internal); 22 23 internal.pop_back(); 24 } 25 public: 26 vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { 27 sort(candidates.begin(), candidates.end()); 28 int end = candidates.size() - 1; 29 vector<int> internal; 30 dfs(0, end, candidates, target, internal); 31 return result; 32 } 33 };