給定一個字符串 s,將 s 分割成一些子串,使每一個子串都是迴文串。指針
返回 s 全部可能的分割方案。code
示例:遞歸
輸入: "aab"
輸出:
[
["aa","b"],
["a","a","b"]
]leetcode
class Solution { public: vector<vector<string>> res; vector<string> path; vector<vector<string>> partition(string s) { res.clear(); path.clear(); back(s, path, 0); return res; } void back(string &s, vector<string> &path, int start) { if (start >= s.size()) { res.push_back(path); return; } for (int i = start; i < s.size(); i++) { if (isPa(s, start, i)) { string str = s.substr(start, i-start+1); path.push_back(str); } else { continue; } back(s, path, i+1); path.pop_back(); } } //雙指針判斷[start,end]是否爲迴文串 bool isPa(string &s, int start, int end) { while (start < end) { if (s[start] == s[end]) { start++; end--; } else { return false; } } return true; } };