-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path131.palindrome-partitioning.cpp
81 lines (78 loc) · 2.13 KB
/
131.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* @lc app=leetcode id=131 lang=cpp
*
* [131] Palindrome Partitioning
*
* https://leetcode.com/problems/palindrome-partitioning/description/
*
* algorithms
* Medium (51.13%)
* Likes: 3086
* Dislikes: 98
* Total Accepted: 298.2K
* Total Submissions: 572.3K
* 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.
*
* A palindrome string is a string that reads the same backward as forward.
*
*
* Example 1:
* Input: s = "aab"
* Output: [["a","a","b"],["aa","b"]]
* Example 2:
* Input: s = "a"
* Output: [["a"]]
*
*
* Constraints:
*
*
* 1 <= s.length <= 16
* s contains only lowercase English letters.
*
*
*/
// @lc code=start
class Solution {
public:
// vector<vector<string>> partition1(string s) {
// vector<vector<string>> result;
// vector<string> currentList;
// dfs(result, s, 0, currentList);
// return result;
// }
vector<vector<string>> partition(string s) {
int L = s.length();
vector<vector<string>> result;
vector<vector<bool>> dp(L, vector<bool>(L, false));
vector<string> currentList;
dfs(result, s, 0, currentList, dp);
return result;
}
void dfs(vector<vector<string>>& result, string& s, int start, vector<string>& currentList, vector<vector<bool>>& dp) {
if (start >= s.length()) {
result.push_back(currentList);
return;
}
for (int end = start; end < s.length(); ++end) {
if (s[start] == s[end] && (end - start <= 2 || dp[start + 1][end - 1])) {
dp[start][end] = true;
currentList.push_back(s.substr(start, end - start + 1));
dfs(result, s, end + 1, currentList, dp);
currentList.pop_back();
}
}
}
bool isPalindrome(string& s, int left, int high) {
while (left < high) {
if (s[left] != s[high])
return false;
++left, --high;
}
return true;
}
};
// @lc code=end