Leetcode#131 Palindrome Partitioning

原题地址

因为要找所有的解,只能搜索+回溯了

看来数据量比较小,关于回文串的判断没有使用动态规划也可以过

代码:

 1 vector<vector<string> > res;
 2 
 3 bool palindromep(string s) {
 4   int i = 0;
 5   int j = s.length() - 1;
 6   while (i < j && s[i] == s[j]) {
 7     i++;
 8     j--;
 9   }
10   return i >= j;
11 }
12 
13 void dfs(string s, vector<string> ans, int pos) {
14   if (pos == s.length())
15     res.push_back(ans);
16   for (int len = 1; pos + len <= s.length(); len++) {
17     if (palindromep(s.substr(pos, len))) {
18       ans.push_back(s.substr(pos, len));
19       dfs(s, ans, pos + len);
20       ans.pop_back();
21     }
22   }
23 }
24 
25 vector<vector<string>> partition(string s) {
26   dfs(s, vector<string>(), 0);
27   return res;
28 }
原文地址:https://www.cnblogs.com/boring09/p/4266215.html