Note palindromic word is divided, not to determine whether a string is a palindrome big string
The general idea:
dfs went just fine.
· See a small conclusion: if required output all possible solutions, often use a depth-first search. If it is required to find the optimal solution, or the number of the solution, often using dynamic programming.
· There is a very powerful point: string reverse iterator rbegin () and rend () , see Figure:
So, to determine whether a string is a palindrome, just one sentence :
return s == string(s.rbegin(),s.rend()); //看s的反向是不是等于s
* Note: substr (the starting point, the string length of the substring )
AC Code:
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
vector<string> cur;
dfs(res,cur,s);
return res;
}
void dfs(vector<vector<string>> &res, vector<string> &cur, string s)
{
if(s=="")
{
res.push_back(cur);
return;
}
for(int i=1;i<=s.size();i++)
{
string sub = s.substr(0,i);
if(isPalindrome(sub))
{
cur.push_back(sub);
dfs(res,cur,s.substr(i,s.size()-i));
cur.pop_back(); //pop_back是移除vector最后一个元素,也就是移除这里加入的sub
}
}
}
bool isPalindrome(string s)
{
return s == string(s.rbegin(),s.rend());
}
};