-
Notifications
You must be signed in to change notification settings - Fork 0
/
131. 分割回文串.cpp
129 lines (129 loc) · 2.39 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
//131. 分割回文串
//给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
//回文串 是正着读和反着读都一样的字符串。
//示例 1:
//输入:s = "aab"
//输出:[["a","a","b"],["aa","b"]]
//示例 2:
//输入:s = "a"
//输出:[["a"]]
//提示:
//1 <= s.length <= 16
//s 仅由小写英文字母组成
#include"leetcode.h"
using namespace std;
static vector<vector<string>>ans;
static vector<string>vec;
static bool check(const string& s)
{
if (s.length() == 1)
return true;
int l = 0, r = s.length() - 1;
while (l <= r)
{
if (s[l++] != s[r--])
{
return false;
}
}
return true;
}
static void dfs(const string& str, int start)
{
//cout << start << endl;
if (start >= str.length())
{
ans.push_back(vec);
//vec.clear();
return;
}
for (int i = 1; i + start <= str.length(); i++)
{
string s = str.substr(start, i);
if (check(s))
{
vec.push_back(s);
dfs(str, start + i);
vec.pop_back();
}
}
}
vector<vector<string>> Solution::partition(string s) {
dfs(s, 0);
return ans;
}
class Solution1 {
public:
vector<vector<string>>ans;
vector<string>vec;
vector<vector<bool>>dp;
void dfs(const string& str, int start)
{
if (start >= str.length())
{
ans.push_back(vec);
return;
}
for (int i = 1; i + start <= str.length(); i++)
{
if (dp[start][i+start-1])
{
vec.push_back(str.substr(start, i));
dfs(str, start + i);
vec.pop_back();
}
}
}
vector<vector<string>> partition(string s) {
int n = s.size();
dp.resize(n,vector<bool>(n,true));
for (int i = n-2; i >= 0; i--)
{
for (int j = i+1; j < n; j++)
{
dp[i][j] = s[i] == s[j] && dp[i + 1][j - 1];
}
}
dfs(s, 0);
return ans;
}
};
class Solution2 {
public:
vector<vector<string>>ans;
vector<string>vec;
vector<vector<int>>dp;
void dfs(const string& str, int start)
{
if (start >= str.length())
{
ans.push_back(vec);
return;
}
for (int i = 1; i + start <= str.length(); i++)
{
if (isPalindrome(str,start,i + start - 1)==1)
{
vec.push_back(str.substr(start, i));
dfs(str, start + i);
vec.pop_back();
}
}
}
int isPalindrome(const string&s,int i,int j)
{
if (dp[i][j])
{
return dp[i][j];
}
if (i >= j)
return 1;
return dp[i][j]=(s[i] == s[j] ? isPalindrome(s, i + 1, j - 1):-1);
}
vector<vector<string>> partition(string s) {
int n = s.size();
dp.resize(n, vector<int>(n));
dfs(s, 0);
return ans;
}
};