Given a string s, partition s such that every substring of the partition is a palindrome.数组
Return all possible palindrome partitioning of s.函数
For example, given s = "aab"
,spa
Returncode
[ ["aa","b"], ["a","a","b"] ]
解题:blog
使用深刻优先搜索的思想;使用递归;递归
从头i = 0开始遍历字符串,找到知足要求的回文列,将其放入结果列表中,继续查找下面的回文字符;字符串
解题步骤:string
一、主函数,创建返回的二维数组,创建存放结果的一维数组,调用递归函数;it
二、递归函数,输入为二维数组ret,一维数组path,字符串str,当前检查到的index值:io
(1)若是index值已经等于str的长度,说明搜索完毕,将path插入ret中,返回;
(2)不然从i从index开始,遍历到str末尾,找index~i范围哪些是回文串:
a. 将回文串摘出放入path中,更新index,继续递归;
b. 从path中pop出放入的回文串,继续遍历循环;
三、返回ret
代码:
1 class Solution { 2 public: 3 vector<vector<string>> partition(string s) { 4 vector<vector<string> > ret; 5 if(s.empty()) 6 return ret; 7 8 vector<string> path; 9 dfs(ret, path, s, 0); 10 11 return ret; 12 } 13 14 void dfs(vector<vector<string> >& ret, vector<string>& path, string& s, int index) { 15 if(index == s.size()) { 16 ret.push_back(path); 17 return; 18 } 19 20 for(int i = index; i < s.size(); ++i) { 21 // find all palindromes begin with index 22 if(isPalindrome(s, index, i)) { 23 path.push_back(s.substr(index, i - index + 1)); 24 dfs(ret, path, s, i+1); 25 path.pop_back(); 26 } 27 } 28 } 29 30 bool isPalindrome(const string& s, int start, int end) { 31 while(start <= end) { 32 if(s[start++] != s[end--]) 33 return false; 34 } 35 return true; 36 } 37 };