LintCode: Combination Sum II
C++
DFS
1 class Solution { 2 public: 3 void help(vector<int> &a, int now, int sum, int target, vector<int> &path, vector<vector<int> > &ans, bool last) { 4 if (sum > target) { 5 return ; 6 } 7 if (now >= a.size()) { 8 if (sum == target) { 9 ans.push_back(path); 10 } 11 return ; 12 } 13 if ((now == 0) || (a[now - 1] != a[now]) || last) { 14 path.push_back(a[now]); 15 help(a, now + 1, sum + a[now], target, path, ans, true); 16 path.pop_back(); 17 } 18 help(a, now + 1, sum, target, path, ans, false); 19 } 20 /** 21 * @param num: Given the candidate numbers 22 * @param target: Given the target number 23 * @return: All the combinations that sum to target 24 */ 25 vector<vector<int> > combinationSum2(vector<int> &num, int target) { 26 // write your code here 27 sort(num.begin(), num.end()); 28 vector<int> path; 29 vector<vector<int> > ans; 30 help(num, 0, 0, target, path, ans, true); 31 return ans; 32 } 33 };
![字节跳动内推](https://img2020.cnblogs.com/blog/323808/202004/323808-20200415172728571-1992447742.jpg)
找我内推: 字节跳动各种岗位
作者:
ZH奶酪(张贺)
邮箱:
cheesezh@qq.com
出处:
http://www.cnblogs.com/CheeseZH/
*
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。