Medium
,String
,Backtracking
,DP
Given a string s
, partition s such that every
substring of the partition is a palindrome. Return all possible palindrome partitioning of s
.
Example 1:
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
Example 2:
Input: s = "a"
Output: [["a"]]
Constraints:
s
contains only lowercase English letters.
class Solution {
public:
vector<vector<string>> ans;
bool isPalindrome(const string& s) {
int start = 0, end = s.size() - 1;
while (start <= end) {
if (s[start++] != s[end--]) return false;
}
return true;
}
void BT(const string& s, vector<string>& path, int cur = 0) {
if (cur == s.size()) {
ans.push_back(path);
return;
}
for (int i = cur; i < s.size(); i++) {
string substring = s.substr(cur, i - cur + 1);
if (isPalindrome(substring)) {
path.push_back(substring);
BT(s, path, i + 1);
path.pop_back();
}
}
}
vector<vector<string>> partition(string s) {
vector<string> path;
BT(s, path);
return ans;
}
};
Yen-Chi ChenSun, Jan 22, 2023
class Solution:
def partition(self, s: str) -> List[List[str]]:
ans = []
def isPalindrome(s):
return s == s[::-1]
def BT(path = [], index = 0):
if index == len(s):
ans.append(path)
return
for i in range(index, len(s)):
sub = s[index:i+1]
if isPalindrome(sub):
BT(path + [sub], i + 1)
BT()
return ans
Yen-Chi ChenSun, Jan 22, 2023