Leetcode 131. Palindrome Partitioning
来源:互联网 发布:方知浮生未歇什么意思 编辑:程序博客网 时间:2024/05/22 10:51
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”]
]
s思路:
1. palindrome回文。要列举所有情况的组合,用backtracking。
2. 回文如何判断?单独写一个函数判断回文。回文用two pointer即可判断!
3. 写代码的时候,发现判断substring是否回文时,出现重复计算,这在backtracking很常见!例如:
s=”aabab”,计算第一个’b’开始的substring后面是否回文就会计算两次:第一次是判断到[“a”,”a”]后需要判断’b’开始的substring;第二次是判断到[“aa”]后又需要判断。
4. 如何避免重复计算?由于需要知道所有的substring是否回文,那么干脆在backtracking前前把所有的情况一次计算出来,然后保存起来,需要用的时候直接查询即可!问题就变成了:如何快速找到所有的组合? 这个问题的简单粗暴方法:枚举所有的可能substring有o(n^2)种,每一种如果独立计算是否回文,那么每一种的复杂度o(n),总共就是o(n^3)。这种做法,显然没用利用回文的性质:回文的扩展性。例如,”abba”,如果发现”bb”是回文,那么”bb”两边的数如果相等,就可以直接判断”abba”是回文。利用回文的这个性质,减少比较的次数,从而复杂度为o(n^2).
5. 刚才做了一道题,需要把计算所有的组合情况分成一步一步,因为有些步骤不一定需要求;这里,把计算substring的回文情况放在一起计算,是因为分开计算会有大量重复的计算,而且这个题是枚举题,需要枚举所有情况,分开做并不会减少运算量。所以一切的原则,就是怎么省计算次数,怎么做,没有固定的模式和方法!
5. 这道题的特点就是:dp+backtracking组合。
//方法1:dp+backtrackingclass Solution {public: void helper(vector<vector<string>>&res, vector<vector<bool>>& isParlin,vector<string>&cur,string&s,int pos){ // if(pos==s.size()){ res.push_back(cur); return; } for(int i=1;i<=s.size()-pos;i++){ if(!isParlin[pos][i+pos-1]) continue; cur.push_back(s.substr(pos,i)); helper(res,isParlin,cur,s,pos+i); cur.pop_back(); } } vector<vector<string>> partition(string s) { // int n=s.size(); vector<vector<bool>> isParlin(n,vector<bool>(n,0)); for(int i=0;i<n;i++){ for(int y=i;y<n;y++){ int x=y-i; if(x==y) isParlin[x][y]=1; else if(y-x==1) isParlin[x][y]=(s[x]==s[y]); else isParlin[x][y]=(isParlin[x+1][y-1]&&s[x]==s[y]); } } vector<vector<string>> res; vector<string> cur; helper(res,isParlin,cur,s,0); return res; }};
- LeetCode 131. Palindrome Partitioning
- [LeetCode]131.Palindrome Partitioning
- [Leetcode] 131. Palindrome Partitioning
- [leetcode] 131.Palindrome Partitioning
- [LeetCode]131. Palindrome Partitioning
- 131. Palindrome Partitioning LeetCode
- Leetcode 131. Palindrome Partitioning
- LeetCode 131. Palindrome Partitioning
- LeetCode *** 131. Palindrome Partitioning
- LeetCode 131. Palindrome Partitioning
- LeetCode-131.Palindrome Partitioning
- 【leetcode】131. Palindrome Partitioning
- [leetcode] 131. Palindrome Partitioning
- 【Leetcode】131. Palindrome Partitioning
- [LeetCode] 131. Palindrome Partitioning
- Leetcode-131. Palindrome Partitioning
- 【LeetCode】131. Palindrome Partitioning
- Leetcode 131. Palindrome Partitioning
- CUDA线程协作之共享存储器“__shared__”&&“__syncthreads()”
- 3D游戏引擎系列十
- Oracle _ SQL语句
- REST服务4种类型
- 数据库常见错误
- Leetcode 131. Palindrome Partitioning
- 1072. Gas Station (30)
- leetcode 48. Rotate Image
- Java语言中字符串的基本操作:
- OA---function
- Codeforces Round #288 (Div. 2)-D. Tanya and Password(欧拉路径及其打印)
- Git中的merge命令实现和工作方式
- 编译Android内核 For nexus 5 以及绕过Android的反调试
- Lock与synchronized 的区别