題目(leecode T131):
給你一個字符串?s
,請你將?s
?分割成一些子串,使每個子串都是?回文串。返回?s
?所有可能的分割方案。
方法:本題是一個分割回文串的問題,是回溯算法的另一類問題。 針對一個字符串,我們要對其進行分割,并且確保分割后生成的子串也必須全都是回文串。分析回溯三部曲
1:傳入參數與返回值:傳入字符串s,以及切割的起始位置startIndex,不需要返回值
2:終止條件:因為切割位置startIndex控制的是切割的起始位置,當startIndex大于等于s.size時,就意味著已經切到了最后,也就該停止了。
3:單層處理邏輯:在單層中我們需要從字符串中截取子串。
在for (int i = startIndex; i < s.size(); i++)
循環中,我們 定義了起始位置startIndex,那么 [startIndex, i] 就是要截取的子串。
首先判斷這個子串是不是回文,如果是回文,就加入在vector<string> path
中,path用來記錄切割過的回文子串。
題解:
?
class Solution {
private:vector<string> path;vector<vector<string>> result;void backtracking(const string& s,int startIndex){if(startIndex >= s.size()){ //終止條件result.push_back(path);return;}for(int i = startIndex; i < s.size(); i++){if(isPalindrome(s, startIndex, i)){string str = s.substr(startIndex, i - startIndex + 1);path.push_back(str);}else{continue;}backtracking(s, i + 1); // 尋找i+1為起始位置的子串path.pop_back(); // 回溯過程,彈出本次已經添加的子串}}bool isPalindrome(const string& s, int start, int end) {for (int i = start, j = end; i < j; i++, j--) {if (s[i] != s[j]) {return false;}}return true;}
public:vector<vector<string>> partition(string s) {result.clear();path.clear();backtracking(s, 0);return result;}
};