<style>
html, body, .ui-content {
background: #222222;
color: #00BFFF;
}
/* 設定 code 模板 */
.markdown-body code,
.markdown-body tt {
background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
color: #ddd;
background-color: #00000036;
}
.hljs-tag {
color: #ddd;
}
.token.operator {
background-color: transparent;
}
/* 設定連結 */
a,
.open-files-container li.selected a {
color: #89FFF8;
}
a:hover,
.open-files-container li.selected a:hover {
color: #89FFF890;
}
</style>
###### tags: `Leetcode`
# 131. Palindrome Partitioning
###### Link : https://leetcode.com/problems/palindrome-partitioning/description/
## 題目
回傳切割原字串後,所有子字串皆為回文的可能
## 程式碼 I
```cpp=
class Solution {
public:
vector<vector<string>> partition(string s) {
ans.clear();
vector<string> current;
backtracking(current, s, 0, 0);
return ans;
}
private:
void backtracking(vector<string> ¤t, string &s, int start, int end){
if(end >= s.size()){
//走訪字串完畢
if(isPalindrome(current) && Count(current) == s.size())
//所有子字串都是回文且字元數量符合string s才將答案放進去
ans.push_back(current);
return;
}
//將自己加入current
current.push_back(s.substr(start, end - start + 1));
backtracking(current, s, end + 1, end + 1);
//不加入current
current.pop_back();
backtracking(current, s, start, end + 1);
return;
}
int Count(vector<string> &s){
int ret = 0;
for(auto &str : s)
for(auto &Char : str)
ret++;
return ret;
}
bool isPalindrome(vector<string> cur){
for(auto &str : cur)
if(!isPalindrome(str))
return false;
return true;
}
bool isPalindrome(string s){
for(int i = 0, j = s.size() - 1;i < j;i++, j--)
if(s[i] != s[j])
return false;
return true;
}
vector<vector<string>> ans;
};
```
## 程式碼 II (Better Solution)
放入current時,只將是回文的放進去,並繼續跑遞迴
```cpp=
class Solution {
public:
vector<vector<string>> partition(string s) {
ans.clear();
vector<string> current;
backtracking(current, s, 0);
return ans;
}
private:
void backtracking(vector<string> ¤t, string &s, int start){
if(start >= s.size()){
ans.push_back(current);
return;
}
for(int end = start;end < s.size();end++){
if(isPalindrome(s, start, end)){
current.push_back(s.substr(start, end - start + 1));
backtracking(current, s, end + 1);
current.pop_back();
}
}
return;
}
bool isPalindrome(string &s, int start, int end){
while(start < end)
if(s[start++] != s[end--])
return false;
return true;
}
vector<vector<string>> ans;
};
```
## Date
### 2023/1/22