给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。 回文串
是正着读和反着读都一样的字符串。
char ***ret = NULL;
int retSize = 0;
int *retColSize = NULL;
char **str = NULL;
int **dp = NULL;
int** isPalindrome(char* s, int start, int end)
{
int len = end - start + 1;
int **dp = (int**)malloc(sizeof(int *) * len);
for(int i = 0; i < len; i++)
{
int *temp = (int*)malloc(sizeof(int) * len);
dp[i] = temp;
}
for(int i = 0; i < len; i++)
{
dp[i][i] = 1;
}
if(end == start)
{
dp[0][0] = 1;
return dp;
}
if(end - start == 1)
{
dp[0][1] = s[end] == s[start];
return dp;
}
//memset(dp, 0, sizeof(dp));
for(int i = 0; i < len; i++)
{
dp[i][i] = 1;
}
for(int i = len - 2; i >= 0; i--)
{
for(int j = i + 1; j < len; j++)
{
if(s[start+i] == s[start+j])
{
dp[i][j] = j - 1> i + 1 ? dp[i+1][j-1] : 1;
//printf("%d\n", dp[i][j]);
}
else
{
dp[i][j] = 0;
}
}
}
//printf("%d\n", dp[0][len-1]);
return dp;
}
void backtrack(char *s, int len, int index, int num)
{
if(len == index)
{
char **temp = (char **)malloc(sizeof(char*) * num);
for(int i = 0; i < num; i++)
{
int l = strlen(str[i]) + 1;
char *tmp = (char*)malloc(sizeof(char) * l);
memcpy(tmp, str[i], sizeof(char) * l);
temp[i] = tmp;
}
ret[retSize] = temp;
retColSize[retSize++] = num;
return;
}
for(int j = index; j < len; j++)
{
if(!dp[index][j])
{
continue;
}
memcpy(str[num], &s[index], sizeof(char) * (j-index+1));
str[num][j-index+1] = '\0';
backtrack(s, len, j+1, num+1);
memset(str[num], 0, sizeof(char) * 20);
}
}
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
char *** partition(char * s, int* returnSize, int** returnColumnSizes){
retSize = 0;
ret = (char***)malloc(sizeof(char **) * 33000);
retColSize = (int *)malloc(sizeof(int) * 33000);
str = (char**)malloc(sizeof(char *) * 20);
for(int i = 0; i < 20; i++)
{
char* temp = (char*)malloc(sizeof(char) * 20);
memset(temp, 0, sizeof(char) * 20);
str[i] = temp;
}
dp = isPalindrome(s, 0, strlen(s) - 1);
backtrack(s, strlen(s), 0, 0);
for(int i = 0; i < 20; i++)
{
free(str[i]);
}
free(str);
*returnSize = retSize;
*returnColumnSizes = retColSize;
return ret;
}
思路:回溯算法+动态规划
使用回溯算法遍历所有可能的字符串,然后使用动态规划判断字符串是否为回文字符串