131. Palindrome Partitioning
题目描述
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”]
]
题解
深度优先搜索,分两种情况,一种是不断开,一种是可断开时断开。
Solution1:
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> result;
vector<string> path;
dfs(s, path, result, 0, 1);
return result;
}
// prev 表示前一个隔板, start表示当前隔板
void dfs(string& s, vector<string>& path,
vector<vector<string>>& result, size_t prev, size_t start) {
if (start == s.size()) {
if (isPalindrome(s, prev, start-1)) {
path.push_back(s.substr(prev, start-prev));
result.push_back(path);
path.pop_back();
}
return;
}
// 不断开
dfs(s, path, result, prev, start+1);
// 断开
if (isPalindrome(s, prev, start-1)) {
path.push_back(s.substr(prev, start-prev));
dfs(s, path, result, start, start+1);
path.pop_back();
}
}
bool isPalindrome(const string& s, int start, int end) {
while(start < end && s[start] == s[end]) {
++start;
--end;
}
return start >= end;
}
};