[leetcode]Palindrome Partitioning
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"] ]
好久木有写C++,手好生,写了很久。。。1016 ms过大集合。。。好像有点慢
思路:
1. 2D dp求出字符串s的回文情况,注意区分aba和aa的情况,解决方法是初始化的时候为1,这样就可以把 f(i, j) = f(i+1, j-1) && s[i] == s[j] 和 s[i] == s[j] 统一起来了
2. 剩下的部分用我的DFS模版写了一下,每次到step1中求出来的isPalin里面去搜,搜到1以后,i = j+1 继续递归下去
class Solution { vector<vector<string>> result; public: vector<vector<bool>> setIsPalin(string s){ int N = s.size(); vector<vector<bool>> f(N, vector<bool>(N, 1)); for(int i = N-1; i >= 0; i--){ for(int j = i+1; j < N; j++){ if(j >= N || i < 0) continue; f[i][j] = f[i+1][j-1] && s[i] == s[j]; } } return f; } void part(int i, int j, vector<string> tmp, string &s, vector<vector<bool>> &isPalin){ if(!isPalin[i][j]) return; tmp.push_back(s.substr(i, j-i+1)); int N = s.size(); if(j == N-1){ result.push_back(tmp); return; } i = j+1; for(int j = i; j < s.size(); j++){ part(i, j, tmp, s, isPalin); } } vector<vector<string>> partition(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function result.clear(); vector<vector<bool>> isPalin = setIsPalin(s); vector<string> tmp; int i = 0; for(int j = i; j < s.size(); j++){ part(i, j, tmp, s, isPalin); } return result; } };