Leetcode#40 Combination Sum II
排序+DFS
代码:
1 vector<vector<int> > res; 2 3 void dfs(vector<int> &num, vector<int> &ans, int pos, int left) { 4 if (left == 0) 5 res.push_back(ans); 6 for (int i = pos; i < num.size() && num[i] <= left; i++) { 7 if (i == pos || num[i] > num[i - 1]) { 8 ans.push_back(num[i]); 9 dfs(num, ans, i + 1, left - num[i]); 10 ans.pop_back(); 11 } 12 } 13 } 14 15 vector<vector<int> > combinationSum2(vector<int> &num, int target) { 16 sort(num.begin(), num.end()); 17 vector<int> ans; 18 dfs(num, ans, 0, target); 19 return res; 20 }