39. 组合总和

image.png

  1. class Solution {
  2. public:
  3. vector<int> path;
  4. vector<vector<int>> result;
  5. void backtracking(vector<int>& candidates,int target,int startIndex)
  6. {
  7. if(target<0)return;
  8. if(target==0)
  9. {
  10. result.push_back(path);
  11. return;
  12. }
  13. for(int i = startIndex;i<candidates.size();i++)
  14. {
  15. path.push_back(candidates[i]);
  16. // 关键点:不用i+1了,表示可以重复读取当前的数
  17. //从与上一层循环相同的位置开始
  18. backtracking(candidates,target-candidates[i],i);
  19. path.pop_back();
  20. }
  21. }
  22. vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
  23. backtracking(candidates,target,0);
  24. return result;
  25. }
  26. };

剪枝

对数组进行排序,再剪枝

  1. class Solution {
  2. public:
  3. vector<int> path;
  4. vector<vector<int>> result;
  5. void backtracking(vector<int>& candidates,int target,int startIndex)
  6. {
  7. if(target==0)
  8. {
  9. result.push_back(path);
  10. return;
  11. }
  12. //target-candidates[i]>=0才进入循环
  13. for(int i = startIndex;i<candidates.size()&&target-candidates[i]>=0;i++)
  14. {
  15. path.push_back(candidates[i]);
  16. backtracking(candidates,target-candidates[i],i);
  17. path.pop_back();
  18. }
  19. }
  20. vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
  21. sort(candidates.begin(),candidates.end());
  22. backtracking(candidates,target,0);
  23. return result;
  24. }
  25. };