131. 分割回文串

题目描述

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

回文串 是正着读和反着读都一样的字符串。

示例 1:

输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]

示例 2:

输入:s = "a"
输出:[["a"]]

提示:

  • 1 <= s.length <= 16
  • s 仅由小写英文字母组成

解答

class Solution {
public:
    vector<vector<string>> res;
    vector<string> path;
    vector<vector<string>> partition(string s) {
        res.clear();
        path.clear();
        backtrack(s, 0);
        return res;
    }

    void backtrack(string &s, int startidx)
    {
        // 分割起点大于等于字符串长度就说明本次分割完成,得到一组结果
        if(startidx >= s.size())
        {
            res.push_back(path);
            return;
        }

        // i 从 startidx 出发判断 [startidx, i]构成的字符串是否回文
        // 若是则加入临时结果中,进行后续的分割
        for(int i = startidx; i < s.size(); i++)
        {
            if(isPalindrome(s, startidx, i))
            {
                string str = s.substr(startidx, i - startidx + 1);
                path.push_back(str);
            }   
            else
            {
                continue;
            }
            backtrack(s, i + 1);
            path.pop_back();
        }
    }

    bool isPalindrome(string &str, int start, int end)
    {
        for(int i = start, j = end; i < j; i++, j--)
        {
            if(str[i] != str[j]) return false;
        }
        return true;
    }
};

你可能感兴趣的:(LeetCode错题集,算法,数据结构,javascript)