文字列sが与えられた場合、各部分文字列が回文になるようにsをいくつかの部分文字列に分割します。
の可能なすべての分割スキームを返します。
例:
入力: "aab"
出力:
[
["aa"、 "b"]、
["a"、 "a"、 "b"]
]
分析:
組み合わせ数の以前の可能な組み合わせスキームの問題と比較して、ここでは文字列が分割され、組み合わせスキームは文字列分割線の位置に依存します。コードは次のとおりです。
class Solution {
public:
vector<vector<string>> ret;
vector<string> path;
void backTracking(const string& s, int index){
if(index >= s.size()){
ret.push_back(path);
return;
}
for(int i = index; i < s.size(); i++) {
if(isPalindrome(s, index, i)){
string str = s.substr(index, i - index + 1);
path.push_back(str);
}else continue;
backTracking(s, i + 1);
path.pop_back();
}
}
bool isPalindrome(const string& s, int index, int end){
for(int i = index, j = end; i < j; ++i, --j){
if(s[i] == s[j]) continue;
else return false;
}
return true;
}
vector<vector<string>> partition(string s) {
backTracking(s, 0);
return ret;
}
};