LeetCode——Palindrome Partition

来源:互联网 发布:网吧电影源码 编辑:程序博客网 时间:2024/05/21 11:11

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"]  ]
思路:此题为分割字符串,使得每个字符串都是回文串,可以枚举所有的可能情况。在枚举过程中,利用两个技术加快枚举速度。
1、动态规划,保存从i到j是否是回文串,减少重复的计算。
2、利用dfs搜索满足条件的分割方式。
代码:
class Solution {public:vector<string> vt;vector<vector<string> > ans;vector<vector<int> > dp;int len;bool dpjudge(string &s, int i, int j) {if (i > j) {return false;}if (dp[i][j] != -1) { //说明已经计算过return dp[i][j];}if (i == j) {return dp[i][j] = 1;}if (s[i] != s[j]) {return dp[i][j] = 0;} else {if (i + 1 == j) {return dp[i][j] = 1;} else {return dp[i][j] = dpjudge(s, i + 1, j - 1);}}}void dfs(string &s, int cnt) {if (cnt == len) {ans.push_back(vt);return;}for (int i = len - 1; i >= cnt; i--) {if (dpjudge(s, cnt, i)) {vt.push_back(s.substr(cnt, i - cnt + 1));dfs(s, i + 1);vt.pop_back();}}}vector<vector<string>> partition(string s) {vt.clear();ans.clear();dp.clear();len = s.length();vector<int> tmp;//初始化dp为-1for (int i = 0; i < len; i++) {tmp.push_back(-1);}for (int j = 0; j < len; j++) {dp.push_back(tmp);}dfs(s, 0);return ans;}};

其中注意容易出错的语句
1、return dp[i][j]=dpjudge(s,i+1,j-1):不能写成return dpjudge(s,i+1,j-1);
2、注意vt.pop_back()语句
0 0
原创粉丝点击