您的位置:首页 > 其它

[LeetCode] Palindrome Partitioning, Solution

2016-01-12 11:10 302 查看
Given a string s[/i], partition s[/i] such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s[/i].
For example, given s[/i] =
"aab"
,
Return
[
["aa","b"],
["a","a","b"]
]


» Solve this problem

[Thoughts]
这种需要输出所有结果的基本上都是DFS的解法。实现如下。

[code]1:       vector<vector<string>> partition(string s) {
2:            vector<vector<string>> result;
3:            vector<string> output;
4:            DFS(s, 0, output, result);
5:            return result;
6:       }
7:       void DFS(string &s, int start, vector<string>& output, vector<vector<string>> &result)
8:       {
9:            if(start == s.size())
10:            {
11:                 result.push_back(output);
12:                 return;
13:            }
14:            for(int i = start; i< s.size(); i++)
15:            {
16:                 if(isPalindrome(s, start, i))
17:                 {
18:                      output.push_back(s.substr(start, i-start+1));
19:                      DFS(s, i+1, output, result);
20:                      output.pop_back();
21:                 }
22:            }
23:       }
24:       bool isPalindrome(string &s, int start, int end)
25:       {
26:            while(start< end)
27:            {
28:                 if(s[start] != s[end])
29:                 return false;
30:                 start++; end--;
31:            }
32:            return true;
33:       }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: