【LeetCode每日一题】131. 分割回文串

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

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

示例 1:

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

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

提示:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-partitioning
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 1 class Solution {
 2 public:
 3     vector<vector<string>> partition(string s) {
 4         vector<vector<string>> res;
 5         backtrack(s, res, {});
 6         return res;
 7     }
 8 
 9     void backtrack(string s, vector<vector<string>>& res, vector<string> path) {
10         if(s.size()==0){
11             res.push_back(path);
12             return;
13         }
14 
15         for(int i=1; i<=s.size(); i++) {
16             string pre = s.substr(0, i);
17             if(isPalindrome(pre)) {
18                 path.push_back(pre);
19                 backtrack(s.substr(i), res, path);
20                 path.pop_back();
21             }
22         }
23     }
24 
25     bool isPalindrome(string s) {
26         if(s.size()==0) return true;
27         int start = 0, end = s.size()-1;
28         while(start<end) {
29            if(s[start]!=s[end])
30                return false;
31            start++;
32            end--;
33         }
34         return true;
35     }
36 };

【笔记】

partition 分割

backtrack 原路返回

palindrome 回文

原文地址:https://www.cnblogs.com/s-zhou/p/14497471.html