代码随想录DAY 27 39. 组合总和 40.组合总和II 131.分割回文串

39. 组合总和

允许重复,框架不变

class Solution {
private:
vector> result;
vector path; 

void transfer(vector& candidates, int target,int sum,int start){
    if(sum>target){
        return;
    }

    if(sum==target){
        result.push_back(path);
        return ;
    }

        //这里从start开始是为了避免重复
    for(int i=start;i> combinationSum(vector& candidates, int target) {
        result.clear();
        path.clear();
        if(candidates.size()==0){
            return result;
        }

        transfer(candidates,target,0,0);
        return result;
    }
};

40.组合总和II

去重就好啦

判断上一个不能与下一个要加入的数字相同

模板还是不变

class Solution {
private:
vector> result;
vector path; 
    void transfer(vector& candidates, int target,int sum,int start){
        if(sum>target){
            return;
        }
        
        if(sum==target){
            result.push_back(path);
            return;
        }

        for(int i=start;istart&&i>0&&candidates[i]==candidates[i-1]){
                continue;
            }

            sum+=candidates[i];
            path.push_back(candidates[i]);
            transfer(candidates,target,sum,i+1);
            sum-=candidates[i];
            path.pop_back();
        }
    }

public:
    vector> combinationSum2(vector& candidates, int target) {
        result.clear();
        path.clear();
        if(candidates.size()==0){
            return result;
        }
        sort(candidates.begin(),candidates.end());
        transfer(candidates,target,0,0);
        return result;
    }
};

131.分割回文串

是否和滑动窗口有些相似?

和上题一样都是在原来的字符串(数组)中判断是否为回文数(相似)

class Solution {
private:
vector> result;
vector path;

void transfer(string&s, int start){
    if(start>=s.size()){
        result.push_back(path);
        return;
    }

    for(int i=start;i> partition(string s) {
        result.clear();
        path.clear();
        transfer(s,0);
        return result;
    }
};

你可能感兴趣的:(算法,leetcode,c++,数据结构)