-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_STOII_0086_partition.cc
63 lines (58 loc) · 1.33 KB
/
Problem_STOII_0086_partition.cc
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
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// @sa https://leetcode-cn.com/problems/palindrome-partitioning/
// @sa Problem_0131_partition.cc
class Solution
{
public:
vector<vector<bool>> getDp(const string &s)
{
int n = s.length();
vector<vector<bool>> dp(n, vector<bool>(n));
for (int i = 0; i < n - 1; i++)
{
dp[i][i] = true;
dp[i][i + 1] = s[i] == s[i + 1];
}
dp[n - 1][n - 1] = true;
for (int i = 2; i < n; i++)
{
int left = 0;
int right = i;
while (left < n && right < n)
{
dp[left][right] = s[left] == s[right] && dp[left + 1][right - 1];
left++;
right++;
}
}
return dp;
}
void process(const string &s, int index, vector<vector<bool>> &dp, vector<string> &path, vector<vector<string>> &ans)
{
if (index == s.length())
{
ans.push_back(path);
return;
}
for (int i = index; i < s.length(); i++)
{
if (dp[index][i])
{
path.push_back(s.substr(index, i - index + 1));
process(s, i + 1, dp, path, ans);
path.pop_back();
}
}
}
vector<vector<string>> partition(string s)
{
vector<vector<bool>> dp = getDp(s);
vector<string> path;
vector<vector<string>> ans;
process(s, 0, dp, path, ans);
return ans;
}
};