-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathplaindrome_str.cpp
53 lines (43 loc) · 1.15 KB
/
plaindrome_str.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
#include <iostream>
#include <vector>
using namespace std;
bool isPalindrome(string s, int start, int end) {
while (start < end) {
if (s[start] != s[end]) {
return false;
}
start++;
end--;
}
return true;
}
vector<vector<string>> partitionPalindrome(string s) {
vector<vector<string>> result;
vector<string> current;
backtrack(s, 0, current, result);
return result;
}
void backtrack(string s, int start, vector<string>& current, vector<vector<string>>& result) {
if (start == s.length()) {
result.push_back(current);
return;
}
for (int end = start; end < s.length(); end++) {
if (isPalindrome(s, start, end)) {
current.push_back(s.substr(start, end - start + 1));
backtrack(s, end + 1, current, result);
current.pop_back();
}
}
}
int main() {
string s = "aab";
vector<vector<string>> partitions = partitionPalindrome(s);
for (auto partition : partitions) {
for (string palindrome : partition) {
cout << palindrome << " ";
}
cout << endl;
}
return 0;
}