LeetCode 131. Palindrome Partitioning--回溯法
来源:互联网 发布:易语言钓鱼源码大全 编辑:程序博客网 时间:2024/05/19 00:41
题目链接
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"]]
1.写一个判断函数 isPalindrome ,判断字符串是不是palindrome(回文(指顺读和倒读都一样的词语))
2.写一个递归函数 split ,参数 head 代表从 head 位置开始找所有能构成回文的字符串(第一个一定是head位置的字符本身),找到后将子串放入 vector 中,再次调用 split 在子串尾位置开始找,当找到所有情况后,即将子串从 vector 中 pop 出。终止递归函数的条件就是当位置 head 已经超过了字符串的长度,这时候我们得到了一个解,将得到的 vector 放进结果 vector<vector> 后直接返回。
3. partition 中调用递归函数 split ,参数 head = 0
代码:
class Solution {public: bool isPalindrome(int head, int tail, string origin) { while (head < tail) { if (origin[head] != origin[tail]) return false; head++; tail--; } return true; } void split(string str, int head, vector<string>& temp, vector<vector<string> >& all) { int len = str.length(); if (head >= len) { vector<string> copy; copy.assign(temp.begin(), temp.end()); all.push_back(copy); return; } for (int i = head; i < len; i++) { if (isPalindrome(head, i, str)) { temp.push_back(str.substr(head, i-head+1)); split(str, i+1, temp, all); temp.pop_back(); } } return; } vector<vector<string> > partition(string s) { vector<vector<string> > answer; vector<string> temp; split(s, 0, temp, answer); return answer; }};
阅读全文
0 0
- LeetCode 131. Palindrome Partitioning--回溯法
- leetcode 131. Palindrome Partitioning-回溯算法
- LeetCode 131. Palindrome Partitioning 树形问题,状态回溯
- 131. Palindrome Partitioning回溯算法
- [leetcode][回溯][DP] Palindrome Partitioning //TODO
- 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
- Leetcode 131. Palindrome Partitioning
- LeetCode 131. Palindrome Partitioning
- LeetCode *** 131. Palindrome Partitioning
- LeetCode 131. Palindrome Partitioning
- LeetCode-131.Palindrome Partitioning
- 【leetcode】131. Palindrome Partitioning
- 6.Less运算(operations)
- 像素翻转Java实现
- app内h5页面调用app功能
- 【题解搬运】PAT_A1016 Phone Bills
- Okhttp网络请求+Rxjava
- LeetCode 131. Palindrome Partitioning--回溯法
- 创建继承于父类Person的子类Studen
- PHP打开文件 fopen
- robot framework
- 机器学习和数据挖掘3——预测波士顿房价
- (作业)使用autolayout和约束实现简单的界面布局
- 学习UDP与TCP的总结
- 阿尔法狗已经够聪明了?DeepMind:没到极限! | 行业
- 怎么办?人工智能可能引发公众的强烈反对 | 观点