forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindrome_Partition.cpp
More file actions
50 lines (42 loc) · 1.15 KB
/
Palindrome_Partition.cpp
File metadata and controls
50 lines (42 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
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"]
]
*/
// A solution using backtracking by Ke Hu (mrhuke@gmail.com)
class Solution {
public:
bool isPalindrome(string s, int i, int j)
{
if (i >= j) return true;
if (s[i] != s[j]) return false;
return isPalindrome(s, i+1, j-1);
}
void partition(string s, int i, vector<string> ¤t, vector<vector<string> > &res)
{
// corner case
if ( i == s.size() ){
res.push_back(current);
return;
}
// DFS
for ( int j = i; j < s.size(); ++j){
if (isPalindrome(s, i, j)){
current.push_back(s.substr(i,j-i+1));
partition(s, j+1, current, res);
current.pop_back();
}
}
}
vector<vector<string>> partition(string s) {
vector<string> current;
vector<vector<string> > res;
partition(s, 0, current, res);
return res;
}
};