您的位置:首页 > 其它

[leetcode][回溯][DP] Palindrome Partitioning //TODO

2015-06-30 09:38 309 查看
题目:

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"]
]

class Solution {
public:
vector<vector<string> > partition(string s) {
vector<vector<string> > res;
vector<string> oneCombination;
partitionCore(s, res, oneCombination);
return res;
}
private:
bool isPalindrome(string s){
int iBeg = 0, iEnd = s.size() - 1;
while (iBeg < iEnd){
if (s[iBeg] != s[iEnd]) return false;
++iBeg; --iEnd;
}
return true;
}
void partitionCore(string s, vector<vector<string>> &res, vector<string> oneCombination){
if (s.empty() && !oneCombination.empty()){
res.push_back(oneCombination);
return;
}
//查找前n个字符可以构成palindrome,然后递归对后半部分求解partition
for (int i = 0; i < s.size(); ++i){
string sSubstr = s.substr(0, i+1);
if (isPalindrome(sSubstr)){
oneCombination.push_back(sSubstr);
partitionCore(s.substr(i + 1), res, oneCombination);
oneCombination.pop_back();
}
}

}
};


DP

void partitionCore(string s, int start, vector<vector<bool> > &table, vector<vector<string> > &res, vector<string> oneCombination){
if (start >= s.size() || table.empty()){
if (!oneCombination.empty()) res.push_back(oneCombination);
return;
}
//查找前n个字符可以构成palindrome,然后递归对后半部分求解partition
for (int i = start; i < s.size(); ++i){
string sSubstr = s.substr(start, i - start + 1);
if (i == start || s[i] == s[start] && (i == start+1 || table[start + 1][i - 1])){
oneCombination.push_back(sSubstr);
partitionCore(s, i + 1,  table, res, oneCombination);
oneCombination.pop_back();
}
}
}
vector<vector<string> > partition(string s) {
//table[i][j]表示s[i]...s[j]是否可以构成回文,是的充分必要条件是s[i]==s[j] && s[i+1]...s[j-1]构成回文
vector<bool> dummy(s.size());
vector<vector<bool> > table(s.size());
for (int i = 0; i < s.size(); ++i){
table[i] = dummy;
}
//table初始化
for (int i = 0; i < s.size(); ++i){
table[i][i] = true;
}
for (int i = s.size() - 1; i >= 0; --i){
for (int j = i + 1; j < s.size(); ++j){
if (s[i] == s[j] && (j == i + 1 || table[i + 1][j - 1])) table[i][j] = true;
else table[i][j] = false;
}
}
vector<vector<string> > res;
vector<string> oneCombination;
partitionCore(s, 0,  table, res, oneCombination);

return res;
}


注:效率还是不太高呀
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: