[Leetcode] 131. Palindrome Partitioning 解题报告
来源:互联网 发布:fft算法的作用 编辑:程序博客网 时间:2024/06/05 10:22
题目:
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"]]
思路:
凡是涉及到求所有可能的结果集合的问题,99%会用到回溯。本题就是一个典型的回溯问题:我们从某个位置start开始,检查从start开始的所有子字符串是否是回文串,如果是,则加入临时结果中,并且递归求解,一旦搜索到结尾,就说明找到了一个符合条件的解,加入集合即可。当然关键在于递归完成一个子字符串之后的回溯,也就是下面代码中p.pop_back()这关键一句。
另外我发现在下面代码中,参数p采用引用比直接用值效率高很多,这是因为如果用值,将会涉及大量的vector复制操作。所以在回溯问题中,能用引用的就尽量用引用,以提高代码执行效率。
代码:
class Solution {public: vector<vector<string>> partition(string s) { vector<vector<string>> ret; if(s.length() == 0) { return ret; } vector<string> line; partition(s, ret, line, 0); return ret; }private: void partition(string& s, vector<vector<string>>& result, vector<string> &p, int start) { if(start == s.length()) { result.push_back(p); return; } for(int i = start; i < s.length(); ++i) { if(isPalindrome(s, start, i)) { p.push_back(s.substr(start, i - start + 1)); partition(s, result, p, i + 1); p.pop_back(); } } } bool isPalindrome(string& s, int left, int right) { int i = left, j = right; while(i < j) { if(s[i] != s[j]) return false; ++i, --j; } return true; }};
0 0
- [leetcode] 131. Palindrome Partitioning 解题报告
- [Leetcode] 131. Palindrome Partitioning 解题报告
- [LeetCode]Palindrome Partitioning,解题报告
- 【LeetCode】Palindrome Partitioning 解题报告
- 【LeetCode】Palindrome Partitioning II 解题报告
- [leetcode] 132. Palindrome Partitioning II 解题报告
- [Leetcode] 132. Palindrome Partitioning II 解题报告
- Palindrome Partitioning解题报告
- leetCode解题报告之Palindrome Partitioning I,II(DFS,DP)
- leetCode解题报告之Palindrome Partitioning I,II(DFS,DP)
- leetCode解题报告之Palindrome Partitioning I,II(DFS,DP)
- leetcode解题笔记-Palindrome Partitioning
- LeetCode 131. Palindrome Partitioning
- [LeetCode]131.Palindrome Partitioning
- [Leetcode] 131. Palindrome Partitioning
- [leetcode] 131.Palindrome Partitioning
- [LeetCode]131. Palindrome Partitioning
- 131. Palindrome Partitioning LeetCode
- 全面解读Moby和LinuxKit,Docker称沟通不善招致误解
- android Studio app clean failed 看过来
- 什么时候该用委托,为什么要用委托,委托有什么好处
- eclipse怎么将java工程转变为web工程
- Linux下查看目录占磁盘大小
- [Leetcode] 131. Palindrome Partitioning 解题报告
- 继承与多态
- POJ3292_Semi-prime H-numbers_变型素数筛&&二分求个数
- POJ 1703-Find them, Catch them(并查集)
- java数据类型
- tomcat端口被占用,解决方法
- SQL 小tips
- 服务器上Oracle System如何修改system用户密码
- 微信小程序开发—(八)canvas绘制图形