Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]
Solution
使用深度优先搜索递归,对于一个字符串,分割为两部分s[0...i]
和s[i+1...s.length - 1]
,如果第一部分是回文串的话,加入结果中,并对第二部分进行递归深搜。
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *columnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
static bool isPalindrome(char* s, int left, int right) {
while (left <= right) {
if (s[left] != s[right]) return false;
left++;
right--;
}
return true;
}
static void dfs(char* s, int** columnSize, int* returnSize, char*** results, int start, int count, char** cur) {
if (start == strlen(s)) {
results[*returnSize] = calloc(count, sizeof(char*));
int i;
for (i = 0; i < count; i++) {
results[*returnSize][i] = calloc(strlen(cur[i]) + 1, sizeof(char));
memcpy(results[*returnSize][i], cur[i], strlen(cur[i]) * sizeof(char));
results[*returnSize][i][strlen(cur[i])] = '\0';
}
(*columnSize)[*returnSize] = count;
(*returnSize)++;
return;
}
int i;
for (i = start; i < strlen(s); i++) {
if (isPalindrome(s, start, i)) {
cur[count] = calloc(i - start + 2, sizeof(char));
memcpy(cur[count], s + start, i - start + 1);
cur[count][i - start + 1] = '\0';
dfs(s, columnSize, returnSize, results, i + 1, count + 1, cur);
}
}
}
char*** partition(char* s, int** columnSizes, int* returnSize) {
char*** results = calloc(512, sizeof(char**));
*columnSizes = calloc(512, sizeof(char*));
*returnSize = 0;
int count = 0;
char** cur = calloc(strlen(s), sizeof(char*));
dfs(s, columnSizes, returnSize, results, 0, count, cur);
return results;
}