-
题目:
给定一个字符串s,分割s使得s的每一个子串都是回文串
返回所有的回文分割结果
例如:给定字符串s=“aab”,
返回
[↵ [“aa”,“b”],↵ [“a”,“a”,“b”]↵ ]Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.For example, given s =“aab”,
Return[↵ ["aa","b"],↵ ["a","a","b"]↵ ]↵
-
idea:
- 首先建立一个二维数组,dp[i][j]代表s字符串i到j的子串为回文串
- 使用dfs遍历字符串,从begin遍历到字符串结尾,假如begin到i为回文串,则加入到当前答案,并dfs子串i…len
- 假如begin>=len,证明当前已经遍历完,将当前答案加入到最终的vector中
-
code
#include <bits/stdc++.h>
class Solution {
public:
bool **dp;
vector<vector<string>> ans;
vector<string> cur;
bool judge_(string s, int begin, int end){
while (end > begin){
if (s[end] != s[begin]) return false;
end--; begin++;
}
return true;
}
void compute_dp(string s, int len){
for (int i = 0; i < len-1; i++){
for (int j = i+1; j < len; j++)
dp[i][j] = judge_(s, i, j);
}
}
void helper(string s, int begin, int len){
if (begin>=len){
ans.push_back(cur);
return;
}
for (int i = begin; i < len; i++){
if (dp[begin][i]){
cur.push_back(s.substr(begin, i-begin+1));
helper(s, i+1, len);
cur.pop_back();
}
}
}
vector<vector<string>> partition(string s) {
int len = s.size();
if(!len) return ans;
dp = new bool*[len];
for (int i = 0; i < len; i++){
dp[i] = new bool[len];
dp[i][i] = true;
}
compute_dp(s, len);
helper(s, 0, len);
return ans;
}
};