-
Notifications
You must be signed in to change notification settings - Fork 1
/
131.palindrome-partitioning.cpp
86 lines (78 loc) · 1.67 KB
/
131.palindrome-partitioning.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
* @lc app=leetcode id=131 lang=cpp
*
* [131] Palindrome Partitioning
*/
// @lc code=start
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution
{
private:
vector<vector<int> > record;
vector<vector<string> > result;
vector<string> cur;
int ispalindrome(const string &s, int i, int j)
{
if (i >= j)
{
return true;
}
if (record[i][j] == -1)
{
if (s[i] == s[j]){
record[i][j] = ispalindrome(s, i + 1, j - 1);
}else{
record[i][j] = 0;
}
}
return record[i][j];
}
void dfs(string s, int i)
{
if (i == s.size())
{
result.push_back(cur);
return;
}
for (int j = i; j < s.size(); ++j)
{
if (ispalindrome(s, i, j) == 0)
{
continue;
}
else
{
cur.push_back(s.substr(i, j-i+1));
dfs(s, j + 1);
cur.pop_back();
}
}
}
public:
vector<vector<string> > partition(string s)
{
record = vector<vector<int> >(s.size(), vector<int>(s.size(), -1));
result = vector<vector<string> >();
for (int i = 0; i < record.size(); ++i)
{
record[i][i] = 1;
}
dfs(s, 0);
return result;
}
};
int main()
{
vector<vector<string> > r = Solution().partition("aab");
for(auto &e : r){
for (auto &ee : e){
cout << ee << ", ";
}
cout << endl;
}
return 0;
}
// @lc code=end