[leetcode-131-Palindrome Partitioning]

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"]
]

思路:

回溯法。注意随时判断子字符串是否是回文串。

     bool isPali(string s)
     {
         int len = s.length();        
         for (int i = 0; i <= s.length()/2;i++)
         {
             if (s[i] != s[len - i - 1])return false;
         }
         return true;
     }
     void parti(vector<vector<string>>& res, vector<string>& pal,string s,int begin)
     {
         if (begin>=s.length())
         {
             res.push_back(pal);
             return;
         }
         for (int i = begin; i < s.length();i++)
         {
             if (isPali(s.substr(begin,i-begin+1)))
             {
                 pal.push_back(s.substr(begin, i - begin + 1));// pal.push_back(s.substr(i, i - begin + 1));这样不对
                 parti(res, pal, s, i + 1);
                 pal.pop_back();
             }
         }
     }
     vector<vector<string>> partition(string s)
     {
         vector<vector<string>> res;
         if (s.empty())return res;
         vector<string> pal;
         parti(res, pal, s, 0);
         return res;
     }
原文地址:https://www.cnblogs.com/hellowooorld/p/7009889.html