-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path00131-palindrome_partitioning.cpp
66 lines (51 loc) · 1.39 KB
/
00131-palindrome_partitioning.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 <iostream>
#include <vector>
using namespace std;
class Solution {
private:
void backtrack(string s, int start, vector<string>& current, vector<vector<string>>& result) {
if (start == s.size()) {
result.push_back(current);
return;
}
for (int i=start; i<s.size(); i++) {
if (isPalindrome(s, start, i)) {
string str = s.substr(start, i - start + 1);
current.push_back(str);
backtrack(s, i + 1, current, result);
current.pop_back();
}
}
}
bool isPalindrome(string s, int left, int right) {
while (left < right) {
if (s[left] != s[right]) return false;
left++;
right--;
}
return true;
}
public:
// SOLUTOIN
vector<vector<string>> partition(string s) {
vector<string> current;
vector<vector<string>> result;
backtrack(s, 0, current, result);
return result;
}
};
int main() {
Solution o;
// INPUT
string s = "aab";
// OUTPUT
auto result = o.partition(s);
cout << "["; for (auto x : result) {
cout << "["; for (auto y : x) {
cout << y << ",";
} cout << "\b],";
} cout << "\b]" << endl;
return 0;
}