分割回文串(回溯)
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文串。返回 s 所有可能的分割方案。
示例 1:
输入:s = "aab" 输出:[["a","a","b"],["aa","b"]]
示例 2:
输入:s = "a" 输出:[["a"]]
class Solution { public: vector<vector<string>> res; vector<string> temp; bool check(string s){ int start=0; int end = s.size()-1; while(start<=end){ if(s[start]!=s[end]){ return false; } start++; end--; } return true; } void backtrack(string s,int start,int end){ if(start>end){ res.push_back(temp); return; } //分别截取长度为1,2,3...的子串进行验证,成功则用剩下的部分递归 for(int i=1;i<=end-start+1;i++){ if(check(s.substr(start,i))){//判断子串是否为回文串 temp.push_back(s.substr(start,i)); backtrack(s,start+i,end); temp.pop_back(); } } } vector<vector<string>> partition(string s) { backtrack(s,0,s.size()-1); return res; } };
浙公网安备 33010602011771号