131. Palindrome Partitioning
阿新 • • 發佈:2017-10-03
emp public lin dfs begin ack subst ssi 總結
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"] ]
解題思路:遞歸回溯,AC之後發現效率比別人的差了點,總結原因是每次判斷子字符是否是回文的時候我都先求了字串,其實可以直接用位置來判斷,然後在temp的push操作時再求substr
classSolution { public: bool isPalindrome(string &s){ for(int i=0,j=s.length()-1;i<j;i++,j--){ if(s[i]!=s[j])return false; } return true; } void dfs(vector<vector<string>> &res, int begin, vector<string>&temp, string& s){if(begin==s.length()){ res.push_back(temp); return; } for(int i=1;i+begin<=s.length();i++){ string str=s.substr(begin,i); if(isPalindrome(str)){ temp.push_back(str); dfs(res,begin+i,temp,s); temp.pop_back(); } } } vector<vector<string>> partition(string s) { vector<vector<string>>res; vector<string>temp; dfs(res,0,temp,s); return res; } };
131. Palindrome Partitioning