46. Permutations
Given a collection of distinct numbers, return all possible permutations.
For example,
[1,2,3]
have the following permutations:
[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
Subscribe to see which companies asked this question
/**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
void swap_num(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void permut(int **result, int *nums, int end, int *rows, int beg)
{
int i;
if (beg == end) //已经是最后一个元素,递归返回
{
(*rows)--;
for(i = 0; i != end; i++)
result[(*rows)][i] = nums[i];
}
else
{
for (i = beg; i != end; i++)
{
swap_num(&nums[beg], &nums[i]);
permut(result,nums, end, rows, beg+1);
swap_num(&nums[beg], &nums[i]);
}
}
}
int** permute(int* nums, int numsSize, int* returnSize) {
int **result, i;
*returnSize = 1;
/* 计算全排列数 */
for(i = numsSize; i > 1; i--)
{
(*returnSize) *= i;
}
/* 为行分配内存 */
result = (int **)malloc((*returnSize)*sizeof(int *)); //6 行
/* 为列分配内存 */
for (i = 0; i != (*returnSize); i++)
*(result + i) = (int *)malloc(numsSize * sizeof(int)); //3列
int rows = *returnSize;
permut(result, nums, numsSize, &rows, 0);
return result;
}