1
1
/*
2
- Author: Annie Kim, [email protected]
2
+
3
3
Date: May 20, 2013
4
+ Update: Oct 06, 2014
4
5
Problem: Palindrome Partitioning
5
6
Difficulty: Easy
6
7
Source: http://leetcode.com/onlinejudge#question_131
19
20
20
21
class Solution {
21
22
public:
22
- vector<vector<string>> res;
23
23
vector<vector<string>> partition (string s) {
24
- res.clear ();
25
- vector<string> part;
26
- partitionRe (s, 0 , part);
27
- return res;
24
+ return partition_2 (s);
28
25
}
29
-
30
- void partitionRe (const string &s, int start, vector<string> &part) {
31
- if (start == s.size ())
32
- {
33
- res.push_back (part);
34
- return ;
26
+ vector<vector<string>> partition_2 (string s) {
27
+ int size = s.size ();
28
+ vector<vector<bool > > dp (size, vector<bool >(size));
29
+ for (int i = size - 1 ; i >= 0 ; --i) {
30
+ for (int j = i; j < size; ++j) {
31
+ dp[i][j]=(s[i]==s[j])&&(j<i+2 ||dp[i+1 ][j-1 ]);
32
+ }
35
33
}
36
- string palindrom;
37
- for (int i = start; i < s.size (); ++i) {
38
- palindrom.push_back (s[i]);
39
- if (!isPalindrome (palindrom)) continue ;
40
- part.push_back (palindrom);
41
- partitionRe (s, i + 1 , part);
42
- part.pop_back ();
34
+ vector<vector<string> > res[size];
35
+ for (int i = size - 1 ; i >= 0 ; --i) {
36
+ for (int j = i; j < size; ++j) {
37
+ if (dp[i][j] == false ) continue ;
38
+ string word = s.substr (i, j - i + 1 );
39
+ if (j == size - 1 ) {
40
+ res[i].push_back (vector<string>{word});
41
+ } else {
42
+ for (auto iter : res[j+1 ]) {
43
+ iter.insert (iter.begin (), word);
44
+ res[i].push_back (iter);
45
+ }
46
+ }
47
+ }
43
48
}
49
+ return res[0 ];
44
50
}
45
51
46
- bool isPalindrome (const string &s) {
47
- int i = 0 , j = s.size ()-1 ;
48
- while (i < j) {
49
- if (s[i] != s[j]) return false ;
50
- i++; j--;
52
+ vector<vector<string>> partition_1 (string s) {
53
+ int size = s.size ();
54
+ vector<vector<bool > > dp (size, vector<bool >(size));
55
+ for (int i = size - 1 ; i >= 0 ; --i) {
56
+ for (int j = i; j < size; ++j) {
57
+ dp[i][j]=(s[i]==s[j])&&(j<i+2 ||dp[i+1 ][j-1 ]);
58
+ }
59
+ }
60
+ vector<vector<string> > res;
61
+ vector<string> path;
62
+ dfs (s, dp, 0 , path, res);
63
+ return res;
64
+ }
65
+ void dfs (string s, vector<vector<bool > > &dp, int start, vector<string> &path, vector<vector<string> > &res) {
66
+ int size = s.size ();
67
+ if (start == size) {
68
+ res.push_back (path);
69
+ }
70
+ for (int i = start; i < size; ++i) {
71
+ if (dp[start][i] == false ) {
72
+ continue ;
73
+ }
74
+ path.push_back (s.substr (start, i - start + 1 ));
75
+ dfs (s, dp, i + 1 , path, res);
76
+ path.pop_back ();
51
77
}
52
- return true ;
53
78
}
54
79
};
0 commit comments