leetcode解题: Palindrome Partitioning (131)

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

1
2
3
4
[
["aa","b"],
["a","a","b"]
]

解法1: O(n*2^n)

常规的backtracking解法,这里我们用一个变量cut来记录当前cut的位置, 然后从cut + 1 开始一个一个个试是否是palindrome。
复杂度的计算是由于一共有O(2^N)种可能的partition。
C++

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
class Solution {
private:
bool isPalindrome(string s) {
for (int i = 0, j = s.size() - 1; i < j; ++i, --j) {
if (s[i] != s[j]) {
return false;
}
}
return true;
}
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
if (s.empty()) {
return res;
}
vector<string> cur;
helper(s, 0, cur, res);
return res;
}
void helper(string s, int cut, vector<string>& cur, vector<vector<string>>& res) {
if (cut == s.size()) {
res.push_back(vector<string>(cur));
return;
}
for (int i = cut + 1; i <= s.size(); ++i) {
string prefix = s.substr(cut, i - cut);
if (!isPalindrome(prefix)) {
continue;
}
cur.push_back(prefix);
helper(s, i, cur, res);
cur.pop_back();
}
}
};

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
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res = new ArrayList<>();
if (s == null || s.length() == 0) {
return res;
}
helper(s, 0, new ArrayList<String>(), res);
return res;
}
private void helper(String s, int pos, List<String> current, List<List<String>> res) {
if (pos == s.length()) {
res.add(new ArrayList<>(current));
return;
}
for (int i = pos + 1; i <= s.length(); i++) {
String cut = s.substring(pos, i);
if (isPalindrome(cut)) {
current.add(cut);
helper(s, i, current, res);
current.remove(current.size() - 1);
}
}
}
private boolean isPalindrome(String s) {
if (s == null || s.length() == 0) {
return true;
}
for (int i = 0, j = s.length() - 1; i < j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
}