您的位置:首页 > 其它

LeetCode: Palindrome Partitioning

2014-04-06 15:13 197 查看
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"]
]
对于这类返回所有结果集合的问题,通常都是使用DFS,递归算法
Soluton:


class Solution {
public:

bool valid(string &str, int st, int end){
while (st < end){
if (str[end] != str[st]){
return false;
}else{
st++;
end--;
}
}
return true;
}

void find(string &s, int st, vector<string> &res, vector<vector<string> > &resAll){
if (st>=s.size()){
resAll.push_back(res);
}else{
for (int i=st;i<s.size();i++){
if (valid(s,st,i)){
res.push_back(s.substr(st,i-st+1));
find(s,i+1,res,resAll);
res.pop_back();
}
}
}
}

vector<vector<string>> partition(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<string> > resAll;
vector<string> res;
find(s,0,res,resAll);
return resAll;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: