131. 分割回文串

131. 分割回文串

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

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

 

示例 1:

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

示例 2:

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

 

提示:

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

 

解析:

dfs暴力即可

class Solution {
public:
    vector<vector<string> > ret;
    void dfs(string& s, int p, vector<string>& tempvec)
    {
        if(p == s.length())
        {
            ret.push_back(tempvec);
            return;
        }
        for(int i = p; i < s.length(); i++)
        {
            int x = p, y = i;
            while(x < y)
            {
                if(s[x] != s[y]) break;
                x++, y--;
            }
            if(x < y) continue;
            tempvec.push_back(s.substr(p, i - p + 1));
            dfs(s, i + 1, tempvec);
            tempvec.pop_back();
        }
    }


    vector<vector<string>> partition(string s) {
        vector<string>  tempvec;
        dfs(s, 0, tempvec);
        return ret;



    }
};

 

posted @ 2022-09-08 22:05  WTSRUVF  阅读(14)  评论(0编辑  收藏  举报