2013.12.15 03:51
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]
Solution:
"Find all combinations that add up to a target value." This is a typical DFS problem.
First step, sort the array.
Second step, depth first searching with pruning technique.
Use some kind of hashing or signature algorithm to make sure no duplicate combinations are put in the result set.
Time complexity is roughly O(2^n), space complexity is O(n).
Accepted code:
1 // 1WA, 1AC, #include <algorithm> 2 // 1WA here, must include algorithm, otherwise sort() would act unexpectedly 3 #include <algorithm> 4 using namespace std; 5 6 class Solution { 7 public: 8 vector<vector<int> > combinationSum2(vector<int> &num, int target) { 9 // Note: The Solution object is instantiated only once and is reused by each test case. 10 int i, j, n; 11 12 n = result.size(); 13 for(i = 0; i < n; ++i){ 14 result[i].clear(); 15 } 16 result.clear(); 17 18 sort(num.begin(), num.end()); 19 v.clear(); 20 count.clear(); 21 i = 0; 22 n = num.size(); 23 // remove duplicates from num 24 while(i < n){ 25 j = i + 1; 26 while(j < n && num[i] == num[j]){ 27 ++j; 28 } 29 v.push_back(num[i]); 30 count.push_back(j - i); 31 i = j; 32 } 33 34 arr.clear(); 35 n = v.size(); 36 dfs(0, n, 0, target); 37 38 return result; 39 } 40 private: 41 vector<int> v; 42 vector<int> arr; 43 vector<int> count; 44 vector<vector<int>> result; 45 46 void dfs(int idx, int n, int sum, int target) { 47 int i, j, k; 48 49 if(sum == target){ 50 result.push_back(arr); 51 return; 52 } 53 54 if(sum > target){ 55 return; 56 } 57 58 for(i = idx; i < n; ++i){ 59 for(j = 1; sum + v[i] * j <= target && j <= count[i]; ++j){ 60 for(k = 0; k < j; ++k){ 61 arr.push_back(v[i]); 62 } 63 dfs(i + 1, n, sum + v[i] * j, target); 64 for(k = 0; k < j; ++k){ 65 arr.pop_back(); 66 } 67 } 68 } 69 } 70 };