-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindromePartitioning.cpp
65 lines (52 loc) · 1.18 KB
/
PalindromePartitioning.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
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool isPalin(string s)
{
string s2 = s;
reverse(s2.begin(), s2.end());
return s == s2;
}
void getAllParts(string s, vector<string> &partitions, vector<vector<string>> &ans)
{
if (s.size() == 0)
{
ans.push_back(partitions);
return;
}
for (int i = 0; i < s.size(); i++)
{
string part = s.substr(0, i + 1);
if (isPalin(part)) // palindrome or not
{
partitions.push_back(part);
getAllParts(s.substr(i + 1), partitions, ans); // recursive call
partitions.pop_back(); // backtracking
}
}
}
vector<vector<string>> partition(string s)
{
vector<vector<string>> ans;
vector<string> partitions;
getAllParts(s, partitions, ans);
return ans;
}
int main()
{
string s = "aab";
vector<vector<string>> result = partition(s);
cout << "Palindrome partitions:\n";
for (const auto &partition : result)
{
cout << "[ ";
for (const auto &word : partition)
{
cout << word << " ";
}
cout << "]\n";
}
return 0;
}