Given a strings, partitionssuch that every substring of the partition is a palindrome.
Return all possible palindrome partitioning ofs.
For example, givens="aab"
,
Return
[ ["aa","b"], ["a","a","b"] ]
Subscribeto see which companies asked this question
//利用深度優先搜索DFS,將字符串劃分為一組回文字符串 class Solution { public: vector> partition(string s) { vector > result; vector path; dfs(s, path, result, 0, 1); return result; } //s[0,prev-1]之間已經處理,保證是回文串 //prev表示s[prev-1]與s[prev]之間的空隙位置,start同理 void dfs(string &s, vector & path, vector >&result, int prev, int start) { if (start == s.size()) { //最後一個隔板 if (ispalindrome(s, prev, start - 1)) { //必須使用 path.push_back(s.substr(prev, start - prev)); result.push_back(path); path.pop_back(); } return; } //不斷開 dfs(s, path, result, prev, start + 1); //如果[prev,start-1]是回文,則可以斷開,也可以不斷開(上一行已經做了) if (ispalindrome(s, prev, start - 1)) { //斷開 path.push_back(s.substr(prev, start - prev)); dfs(s, path, result, start, start + 1); path.pop_back(); } } //判斷子串是否為回文 bool ispalindrome(const string &s, int start, int end) { while (start < end && s[start] == s[end]) { ++start; --end; } return start >= end; } };