您的位置:首页 > 其它

LeetCode Palindrome Partitioning

2014-09-15 08:42 288 查看


Palindrome Partitioning

 Total Accepted: 18645 Total
Submissions: 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 Total
Submissions: 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;
}
};




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dfs dp 回顾 LeetCode