标签:style oid ret sub art color tor 字符 ++
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
class Solution { 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; } };
标签:style oid ret sub art color tor 字符 ++
原文地址:http://www.cnblogs.com/tsunami-lj/p/7623034.html