Create 131. Palindrome Partitioning.md

This commit is contained in:
唐树森 2019-07-19 23:31:43 +08:00 committed by GitHub
parent cd18d04b78
commit 4141743d8f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,45 @@
# [131. Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/)
# 思路
由于是**求所有情况那一般就可以用DFS来考虑要形成这种条件反射**。
我们从s的开头往后遍历用out数组来存放中间结果: 将已经检测好的回文子串放到字符串数组out中每当s遍历完了之后
将out加入结果res中。那么在DFS递归函数中我们必须要知道当前遍历到的位置可用变量start来表示所以在DFS递归函数中
如果start等于字符串s的长度说明已经遍历完成递归出口将out加入结果数组res中并返回。否则就从start处开始进行深度优先搜索
即判断一个字符,或两个字符,或三个字符...是否是回文串,若子串是回文串那么我们将其加入out并且调用DFS递归函数
注意DFS后要恢复out的状态。
# C++
``` C++
class Solution {
private:
bool isPalindrome(string &s, int low, int high){ // 判断s[start,...,end]是否是回文串
while(low < high){
if(s[low] != s[high]) return false;
low++;
high--;
}
return true;
}
void DFS(vector<vector<string>> &res, vector<string> &out, string &s, int start){
if(start == s.size()){
res.push_back(out);
return;
}
for(int i = start; i < s.size(); i++){
if(isPalindrome(s, start, i)){
out.push_back(s.substr(start, i-start+1));
DFS(res, out, s, i + 1);
out.pop_back(); // 注意DFS后要恢复out的状态
}
}
}
public:
vector<vector<string>> partition(string s) {
vector<vector<string>>res{};
vector<string>out{};
DFS(res, out, s, 0);
return res;
}
};
```