-
Notifications
You must be signed in to change notification settings - Fork 1
/
131.cpp
66 lines (61 loc) · 2.07 KB
/
131.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
// 131. Palindrome Partitioning - https://leetcode.com/problems/palindrome-partitioning
#include "bits/stdc++.h"
#include "gtest/gtest.h"
using namespace std;
// Trick: store vector<string> path_so_far.
class Solution {
private:
vector<vector<string>> result;
vector<deque<bool>> dp;
void run_is_palindrome_dp(const string &s) {
int n = (int)s.length();
dp.resize(n, deque<bool> (n, false));
for (int idx = 0; idx < n; ++idx) {
dp[idx][idx] = true;
}
for (int idx = 0; idx < n - 1; ++idx) {
dp[idx][idx + 1] = (s[idx] == s[idx + 1]);
}
for (int len = 3; len <= n; ++len) {
for (int start = 0; start + len - 1 < n; ++start) {
int finish = start + len - 1;
dp[start][finish] = (s[start] == s[finish]) ? dp[start + 1][finish - 1] : false;
}
}
}
bool is_palindrome(const string &str, int L, int R) {
return dp[L][R];
// for (int idx = 0; idx < (R - L + 1) / 2; ++idx) {
// if (str[L + idx] != str[R - idx]) {
// return false;
// }
// }
// return true;
}
void helper(const string &str, int start, int R,
vector<string> path_so_far) {
if (start == R + 1) {
result.emplace_back(path_so_far);
}
for (int finish = start; finish <= R; ++finish) {
if (!is_palindrome(str, start, finish)) { continue; }
int len = finish - start + 1;
path_so_far.emplace_back(str.substr(start, len));
// str[start:finish] is palindrome -> continue search
// from finish + 1;
helper(str, finish + 1, R, path_so_far);
path_so_far.pop_back();
}
}
public:
vector<vector<string>> partition(string s) {
run_is_palindrome_dp(s);
helper(s, 0, (int)s.length() - 1, {});
return result;
}
};
int main(int argc, char **argv) {
ios::sync_with_stdio(false);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}