代码仍然出自代码随想录,此处用于记录。主要是回溯方法的应用和剪枝的具体处理。
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>>res;
vector<int>path;
void backtracking(vector<int>&candidates,int target,int sum, int startIndex){
if (sum == target){
res.push_back(path);
return;
}
//sum+candidates[i] + sum > target,终止遍历(此处进行剪枝)
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++){
sum += candidates[i];
path.push_back(candidates[i]);
backtracking(candidates,target,sum,i);//此处是因为可以使用多次
sum -= candidates[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target)
{
sort(candidates.begin(),candidates.end());//事先对数据进行排序
backtracking(candidates,target,0,0);
return res;
}
};
int main()
{
vector<int>candidates = {2,3,6,7};
int target = 7;
vector<vector<int>> res = Solution().combinationSum(candidates,target);
for (int i = 0; i < res.size(); i++){
for (int j = 0; j < res[i].size(); j++){
cout << " " << res[i][j];
}
cout << endl;
}
return 0;
}