# 46. 全排列

·  阅读 55

### 实现

``````int getValue(int n)
{
for (int i = n - 1; i >= 1; i--) {
n *= i;
}
return n;
}

void swap(int *nums, int i, int j)
{
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}

void backtracking(int *nums, int numsSize, int *returnSize, int **returnColumnSizes, int idx, int **result)
{
if (idx  == numsSize - 1) {    // i 是最后一个，全交换过了
result[*returnSize] = (int*)malloc(sizeof(int) * numsSize);
(*returnColumnSizes)[*returnSize] = numsSize;
for (int i = 0; i < numsSize; i++) {
result[*returnSize][i] = nums[i];
}
(*returnSize)++;
return;
}
for (int i = idx; i < numsSize; i++) {

swap(nums, i, idx);
backtracking(nums, numsSize, returnSize, returnColumnSizes, idx + 1, result);
swap(nums, i, idx);
}
}

int **permute(int *nums, int numsSize, int *returnSize, int **returnColumnSizes)
{
*returnSize = 0;
*returnColumnSizes = (int*)malloc(sizeof(int*) * getValue(numsSize));   // 排列组合次
if (nums == NULL || numsSize == 0) {
returnColumnSizes = NULL;
return NULL;
}

int **result = (int**)malloc(sizeof(int*) * getValue(numsSize));
memset(*returnColumnSizes, 0, sizeof(int) * getValue(numsSize));
memset(result, 0, sizeof(int*) * getValue(numsSize));

backtracking(nums, numsSize, returnSize, returnColumnSizes, 0, result);
return result;
}