题目:
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"
,
Return
[ ["aa","b"], ["a","a","b"] ]
解答:
DFS + isPalindrome判断(在这道题目最大的收获是意识到在能用引用的时候一定要用引用,复制很耗内存也会很耗时间)
class Solution { public: bool isPalindrome(string s) { int len = s.length(); int l = 0; int r = len - 1; while(l <= r) { if(s[l] == s[r]) { l++; r--; } else return false; } return true; } void DFS(int start, string s,vector<string> &temp) { if(start == s.length()) { res.push_back(temp); return; } for(int i = start;i < s.length();++i) { if(isPalindrome(s.substr(start,i - start + 1))) { temp.push_back(s.substr(start,i - start + 1)); DFS(i + 1,s,temp); temp.pop_back(); } } } vector<vector<string>> partition(string s) { vector<string> temp; DFS(0,s,temp); return res; } private: vector<vector<string>> res; };