leetcode: Combination Sum II
http://oj.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: All numbers (including target) will be positive integers. Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). 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解决了,那么这题只要改一行代码,因为每个数字只能出现一次。
1 class Solution { 2 public: 3 void internalCombinationSum2(vector<int> &num, 4 int start, 5 int sum, 6 int target, 7 vector<int> &combination, 8 vector<vector<int> > &result) { 9 int size = num.size(); 10 11 if (sum == target) { 12 result.push_back(combination); 13 14 return; 15 } 16 else if ((start >= size) || (sum > target)) { 17 return; 18 } 19 20 for (int i = start; i < size; ) { 21 combination.push_back(num[i]); 22 internalCombinationSum2(num, i + 1, sum + num[i], target, combination, result); 23 combination.pop_back(); 24 25 int j = i + 1; 26 27 while (j < size) { 28 if (num[i] == num[j]) { 29 ++j; 30 } 31 else { 32 break; 33 } 34 } 35 36 i = j; 37 } 38 } 39 40 vector<vector<int> > combinationSum2(vector<int> &num, int target) { 41 vector<vector<int> > result; 42 vector<int> combination; 43 44 sort(num.begin(), num.end()); 45 internalCombinationSum2(num, 0, 0, target, combination, result); 46 47 return result; 48 } 49 };