DAY29
39组合总和
- 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++)
- {
- path.push_back(candidates[i]);
- sum+=candidates[i];
- backtracking(candidates,target,sum,i);
- sum-=candidates[i];
- path.pop_back();
- }
- return ;
- }
- public:
- vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
- result.clear();
- path.clear();
- backtracking(candidates,target,0,0);
- return result;
- }
- };
40组合总和ii
记住used数组:记录同一分支上的是否用过。语言表述见代码随想录网站。
- class Solution {
- private:
- vector<vector<int>> result;
- vector<int> path;
- void backtracking(vector<int>& candidates,int target,int sum,int startindex,vector<bool>&used){
- if(sum>target) return;
- if(sum==target){
- result.push_back(path);
- return ;
- }
- for(int i=startindex;i<candidates.size()&&sum+candidates[i]<=target;i++){
- if(i>0&&candidates[i]==candidates[i-1]&&used[i-1]==false) continue;
- used[i]=true;
- path.push_back(candidates[i]);
- sum+=candidates[i];
- backtracking(candidates,target,sum,i+1,used);
- used[i]=false;
- path.pop_back();
- sum-=candidates[i];
- }
- return ;
- }
- public:
- vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
- result.clear();
- path.clear();
- vector<bool> used(candidates.size(),false);
- sort(candidates.begin(),candidates.end());
- backtracking(candidates,target,0,0,used);
- return result;
- }
- };
131分割回文串
记:回溯组合题,答案要在叶子节点上,这样来构造
- class Solution {
- private:
- bool ishuiwen(string s){
- for(int i=0,j=s.size()-1;i<j;i++,j--){
- if(s[i]!=s[j]) return false;
- }
- return true;
- }
- vector<vector<string>> result;
- vector<string> path;
- void backtracking(string s,int startindex){
- if(startindex>=s.size()) {
- result.push_back(path);
- return ;
- }
- for(int i=startindex;i<s.size();i++){
- string tmpstr=s.substr(startindex,i-startindex+1);
- if(!ishuiwen(tmpstr)) continue;
- path.push_back(tmpstr);
- backtracking(s,i+1);
- path.pop_back();
- }
- return;
- }
- public:
- vector<vector<string>> partition(string s) {
- result.clear();
- path.clear();
- backtracking(s,0);
- return result;
- }
- };