Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
题意简单明了。
解法:要找到所有的划分方法,应想到穷举。
class Solution { public: bool isPalindrome(string s){ for(size_t i=0; i<s.size()/2; i++) if(s[i] != s[s.size()-1-i]) return false; return true; } vector<vector<string>> partition(string s) { vector<vector<string>> ret; vector<string> temp; dfs(s, 0, temp, ret); return ret; } void dfs(string& s, int idx, vector<string>& temp, vector<vector<string>>& ret){ if(idx == s.size()){ ret.push_back(temp); return; } for(size_t i=1; i<=s.size()-idx; i++){ string prefix = s.substr(idx, i); if(isPalindrome(prefix)){ temp.push_back(prefix); dfs(s, idx+i, temp, ret); temp.pop_back(); } } } };