class Solution {
public:
vector<vector<string>> ans; //答案
vector<vector<bool>> flag; //i, j表示i - j是否是回文串
vector<string> temp; //子串
vector<vector<string>> partition(string s) {
int n = s.size();
flag.assign(n, vector<bool>(n, false)); //赋值,默认为true
backtrack(s, 0, n);
return ans;
}
bool isPalindrome(const string& s, int i, int j) { //记忆化搜索
if(flag[i][j])
return true;
if(i >= j) //"aa"这种情况会出错
return flag[i][j] = true;
return flag[i][j] = (s[i] == s[j] && isPalindrome(s, i + 1, j - 1)); //i == j并且 i+1 - j-1 是回文数
}
void backtrack(const string& s, int i, int n){
if(i == n){
ans.push_back(temp);
return;
}
for(int j = i; j < n; ++j){
if(isPalindrome(s, i, j)){
temp.push_back(s.substr(i, j - i + 1));
backtrack(s, j + 1, n);
temp.pop_back();
}
}
}
};
Accepted
32/32 cases passed (100 ms)
Your runtime beats 84.45 % of cpp submissions
Your memory usage beats 74.6 % of cpp submissions (73.9 MB)