代码随想录算法训练营第二十七天| 39. 组合总和、40.组合总和II、131.分割回文串

代码随想录算法训练营第二十七天| 39. 组合总和、40.组合总和II、131.分割回文串

  • 39. 组合总和
  • 40.组合总和II
  • 131.分割回文串

39. 组合总和

题目链接
文章讲解

class Solution {
public:
    vector<vector<int>> ans;
    vector<int> path;

    void backtracking(int start, int count, const vector<int>& candidates) {
        if (count == 0) {
            ans.push_back(path);
            return;
        }
        for (int i = start; i < candidates.size() && count - candidates[i] >= 0; i++) {
            path.push_back(candidates[i]);
            backtracking(i, count - candidates[i] , candidates);
            path.pop_back();
        }
    }

    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        backtracking(0, target, candidates);
        return ans;
    }
};

40.组合总和II

题目链接
文章讲解

class Solution {
public:
    vector<vector<int>> ans;
    vector<int> path;

    void backtracking(int start, int count, vector<int>& candidates) {
        if (count == 0) {
            ans.push_back(path);
            return;
        }
        for (int i = start; i < candidates.size() && count - candidates[i] >= 0; i++) {
            if (i != start && candidates[i] == candidates[i - 1]) continue;
            path.push_back(candidates[i]);
            backtracking(i + 1, count - candidates[i], candidates);
            path.pop_back();
        }
    }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        backtracking(0, target, candidates);
        return ans;
    }
};

131.分割回文串

题目链接
文章讲解

class Solution {
public:
    vector<vector<string>> ans;
    vector<string> path;

    bool isPalindrome(const string& s, int begin, int end) {
        while (begin < end)
            if (s[begin++] != s[end--])
                return false;
        return true;
    }

    void backtracking(int idx, const string& s) {
        if (idx == s.size()) {
            ans.push_back(path);
            return;
        }
        for (int i = 0; i < s.size() - idx; i++) {
            if (isPalindrome(s, idx, idx + i)) {
                path.push_back(s.substr(idx, i + 1));
                backtracking(idx + i + 1, s);
                path.pop_back();
            }
        }
    }

    vector<vector<string>> partition(string s) {
        backtracking(0, s);
        return ans;
    }
};

你可能感兴趣的:(算法)