LeetCode Palindrome Partitioning
2014-09-15 08:42
288 查看
Palindrome Partitioning
Total Accepted: 18645 TotalSubmissions: 71813My Submissions
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"] ]
思路:
这一题为什么没有想到深搜呢?一般要把所有答案都遍历一边的题目都需要深搜。回顾题目word break 2.
Word Break II
Total Accepted: 7703 TotalSubmissions: 50334My Submissions
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s =
"catsanddog",
dict =
["cat", "cats", "and", "sand", "dog"].
A solution is
["cats and dog", "cat sand dog"].
这一题采用深搜的话复杂度过高,原因是深搜的失败率过高。失败率过高的原因在于每个切割方法与切割点前后的字串都有关系。所以,最终答案采用了dp+dfs的策略。使用dp事先算出一个方向上(假设为是否能够到达终点)是否成功。再dfs时,再加上判断是否能够从起点到达分割点,就能够完成全部判断。
见http://blog.csdn.net/kiki_yu/article/details/24603089
代码:
class Solution { public: vector<vector<string> > partition(string s) { vector<vector<string> > ans; vector<string> cur; dfs(0, s.length(), s, cur, ans); return ans; } void dfs(int start, int depth, string s, vector<string> & cur, vector<vector<string> > &ans) { if (start == depth) { ans.push_back(cur); return; } for (int i = start; i < depth; i++) { if (isPalindrome(s, start, i)) { cur.push_back(s.substr(start, i - start + 1)); dfs(i + 1, depth, s, cur, ans); cur.pop_back(); } } } bool isPalindrome(string s, int b, int e) { for (int i = b, j = e; i < j; i++, j--) { if (s[i] != s[j]) return false; } return true; } };
相关文章推荐
- LeetCode OJ Palindrome Partitioning
- [LeetCode] Palindrome Partitioning II
- Leetcode 132. Palindrome Partitioning II
- LeetCode之Palindrome Partitioning II
- Leetcode Palindrome Partitioning II
- leetcode -- Palindrome Partitioning II
- LeetCode-Palindrome Partitioning II-回文分割-DP优化
- LeetCode-Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- 【LeetCode】Palindrome Partitioning I && II
- [leetcode]Palindrome Partitioning II
- LeetCode "Palindrome Partitioning"算法时间复杂度分析
- 【leetcode】Palindrome Partitioning II
- LEETCODE: Palindrome Partitioning II
- LeetCode Palindrome Partitioning II
- LeetCode 132. Palindrome Partitioning II
- LeetCode OJ Palindrome Partitioning II
- leetcode:Palindrome Partitioning II
- leetcode - Palindrome Partitioning II
- Palindrome Partitioning II Leetcode Python