1. 程式人生 > >LeetCode 131. 分割回文串(Palindrome Partitioning)

LeetCode 131. 分割回文串(Palindrome Partitioning)

題目描述

 

給定一個字串 s,將 s 分割成一些子串,使每個子串都是迴文串。

返回 s 所有可能的分割方案。

示例:

輸入: "aab"
輸出:
[
  ["aa","b"],
  ["a","a","b"]
]

 

解題思路

 

回溯思想。首先遍歷字串的各個子字串,記錄它們是否為迴文串,然後對字串各個索引遞迴判斷迴文串並加入到結果集合中。

 

程式碼

 

 1 class Solution {
 2 public:
 3     vector<vector<string
>> partition(string s) { 4 vector<vector<string>> res; 5 vector<vector<int>> strHuiwen(s.length(), vector<int>(s.length(), 0)); 6 vector<string> temp; 7 for(int i = 0; i < s.length(); i++) 8 for(int j = i; j < s.length(); j++)
9 if(isHuiwen(s.substr(i, j - i + 1))) 10 strHuiwen[i][j] = 1; 11 huiwen(s, 0, res, temp, strHuiwen); 12 return res; 13 } 14 void huiwen(string s, int idx, vector<vector<string>> &res, vector<string> &temp, vector<vector<int
>> strHuiwen){ 15 if(idx == s.length()){ 16 res.push_back(temp); 17 return; 18 } 19 for(int i = idx; i < s.length(); i++){ 20 if(strHuiwen[idx][i]){ 21 temp.push_back(s.substr(idx, i - idx + 1)); 22 huiwen(s, i + 1, res, temp, strHuiwen); 23 temp.pop_back(); 24 } 25 } 26 } 27 bool isHuiwen(string s){ 28 for(int i = 0; i < s.length() / 2; i++) 29 if(s[i] != s[s.length() - i - 1]) return false; 30 return true; 31 } 32 };