题目链接:https://leetcode.com/problems/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.
Note:
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]
思路:和39. Combination Sum差不多,只是这个每个数只能用一次,值得注意的是相同的数如果不做判断可能会产生相同的序列。因此在同一层的递归中,应当跳过重复的数。
代码如下:
class Solution { public: void DFS(vector<int>& candidates, vector<int> vec, int target, int index, int sum) { if(sum > target) return; if(sum == target) { result.push_back(vec); return; } for(int i = index; i< candidates.size(); i++) { vec.push_back(candidates[i]); DFS(candidates, vec, target, i+1, sum + candidates[i]); while(i < candidates.size() && candidates[i] == candidates[i+1])//去掉相同的值 i++; vec.pop_back(); } } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); if(candidates.size() == 0 || target < candidates[0]) return result; vector<int> vec; int index = 0, sum = 0; DFS(candidates, vec, target, index, sum); return result; } private: vector<vector<int>> result; };