一、题意
二、解答过程
回溯三部曲:
- 确定参数
- 确定终止条件
- 确定单层递归逻辑
class Solution { private: vector<vector<int>>result; vector<int> path; void backtracking(vector<int>&candidates,int target,int sum,int startIndex) { if(sum>target) { return; } if(sum==target) { result.push_back(path); return; } for (int i = startIndex; i < candidates.size(); i++) //剪枝操作 //for(int i=startIndex;i<candidates.size()&&sum+candidates[i]<=target;i++) { /* code */ sum+=candidates[i]; path.push_back(candidates[i]); //不需要i+1表示可以重复读取当前的数 backtracking(candidates,target,sum,i); sum-=candidates[i]; path.pop_back(); } } public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { result.clear(); path.clear(); backtracking(candidates,target,0,0); return result; } };
剪枝操作的理解,就是for循环那里做改动: