代码实现:
回溯
/** * 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(). */ int **res; int resSize; int *path; int pathSize; int *vis; void dfs(int *nums, int numsSize) { if (pathSize == numsSize) { res[resSize] = malloc(sizeof(int) * pathSize); memcpy(res[resSize], path, sizeof(int) * pathSize); resSize++; return; } for (int i = 0; i < numsSize; i++) { if (vis[i]) { continue; } path[pathSize] = nums[i]; pathSize++; vis[i] = 1; dfs(nums, numsSize); pathSize--; vis[i] = 0; } } int** permute(int *nums, int numsSize, int *returnSize, int **returnColumnSizes) { res = malloc(sizeof(int*) * 1000); path = malloc(sizeof(int) * numsSize); vis = malloc(sizeof(int) * numsSize); memset(vis, 0, sizeof(int) * numsSize); resSize = pathSize = 0; dfs(nums, numsSize); *returnSize = resSize; *returnColumnSizes = malloc(sizeof(int) * resSize); for (int i = 0; i < resSize; i++) { (*returnColumnSizes)[i] = numsSize; } return res; }