链接: 官方解题思路.
这个错误害我找了好久好久!!长记性啊 (*returnSize)++; //错在没打上小括号!!!!!!!!!!!!!!
/**
* 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().
*/
void dfs(int* nums,int numsSize,char* used,int* path,int depth,int **res,int* returnSize,int** returnColumnSizes)
{
int i;
if(depth == numsSize) { //说明所有数字全部选择完毕,一种排列已选好
res[(*returnSize)] = malloc(sizeof(int) * numsSize);
memcpy(res[*returnSize], path, sizeof(int) * numsSize);
(*returnColumnSizes)[*returnSize] = numsSize;
(*returnSize)++; //错在没打上小括号!!!!!!!!!!!!!!!!!!!!
return;
}
for(i = 0;i < numsSize;i++) {
if(used[i] == 0) { //used[i]=0表示还没使用过
path[depth] = nums[i];
used[i] = 1;
dfs(nums,numsSize,used,path,depth+1,res,returnSize,returnColumnSizes);
used[i] = 0; //回溯
}
}
}
int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){
// if(numsSize == 0) return returnColumnSizes;
int i;
int **res = NULL;
int path[numsSize];
char used[numsSize];
//1,计算结果数量
*returnSize = 1;
for (i = 2; i <= numsSize; i++)
*returnSize = *returnSize * i;
//2,申请空间
res = malloc(*returnSize * sizeof(int *));
*returnColumnSizes = malloc(*returnSize * sizeof(int));
//returnColumnSizes = (int**)malloc(sizeof(int*) * resSize);
memset(used, 0, numsSize);
*returnSize = 0;
dfs(nums,numsSize,used,path,0,res,returnSize,returnColumnSizes);
return res;
}