-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path131.palindrome-partitioning.0.cpp
More file actions
74 lines (71 loc) · 1.74 KB
/
131.palindrome-partitioning.0.cpp
File metadata and controls
74 lines (71 loc) · 1.74 KB
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
/*
* @lc app=leetcode id=131 lang=cpp
*
* [131] Palindrome Partitioning
*
* https://leetcode.com/problems/palindrome-partitioning/description/
*
* algorithms
* Medium (42.74%)
* Likes: 1168
* Dislikes: 48
* Total Accepted: 185.4K
* Total Submissions: 430.1K
* Testcase Example: '"aab"'
*
* Given a string s, partition s such that every substring of the partition is
* a palindrome.
*
* Return all possible palindrome partitioning of s.
*
* Example:
*
*
* Input: "aab"
* Output:
* [
* ["aa","b"],
* ["a","a","b"]
* ]
*
*
*/
// @lc code=start
class Solution {
public:
vector<vector<string>> partition(string s) {
if (s.empty())
return {};
vector<vector<string>> result;
vector<string> cur;
m_ = vector<vector<int>>(s.length(), vector<int>(s.length(), -1));
partition(s, 0, cur, result);
return result;
}
private:
vector<vector<int>> m_;
void partition(const string &s, int start, vector<string> &cur, vector<vector<string>> &result) {
if (start == s.length()) {
result.push_back(cur);
return;
}
for (int len = 1; len + start - 1 < s.length(); ++len) {
if (isPalindrome(s, start, start + len - 1)) {
cur.emplace_back(s.substr(start, len));
partition(s, start + len, cur, result);
cur.pop_back();
}
}
return;
}
bool isPalindrome(const string &s, int i, int j) {
if (i >= j)
return true;
if (m_[i][j] != -1)
return m_[i][j];
if (s[i] == s[j])
return m_[i][j] = isPalindrome(s, i + 1, j - 1);
return m_[i][j] = 0;
}
};
// @lc code=end