给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
给出没有顺序的一组数组,把所有的排列输出。
除了时间复杂度上超级垃圾外还好
参照第三十一题,已前一个为基础,计算下一个的值,复制给结果。虽然慢但是直白啊。
也印证了中国古话,前事不忘后事之师,温故而知新啊。
详细解释关注 B站 【C语言全代码】学渣带你刷Leetcode 不走丢 https://www.bilibili.com/video/BV1C7411y7gB
#include
#include
#define MAX_SIZE 1024
/**
* 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 factor(int n)
{
int ret = 1;
int i = 1;
for (; i <= n; ++i)
{
ret *= i;
}
return ret;
}
void reverse(int* nums,int begin,int end)
{
int temp;
while(begin= 0 && nums[i + 1] <= nums[i])
{
i--;
}
if (i >= 0)
{
int j = numsSize - 1;
while (j >= 0 && nums[j] <= nums[i])
{
j--;
}
swap(nums, i, j);
}
reverse(nums,i+1,numsSize-1);
}
int compare(void *p1, void *p2)
{
return *(int*)p1 - *(int*)p2;
}
int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes)
{
int malloc_len = MAX_SIZE;
//1.初始化返回数组
//1.初始化返回数组
int **ret_array = malloc(sizeof(int*) * malloc_len); //返回结果的二维数组
int i;
for ( i = 0; i < malloc_len; i++)
{
int *ret_col = malloc(sizeof(int) * malloc_len); //定义返回的ret_col的大小 一个一维数组
ret_array[i] = ret_col;
}
//2. 排序
qsort(nums, numsSize, sizeof(int), compare);
int k;
int j;
int col=factor(numsSize);
int *col_size = malloc(sizeof(int) * malloc_len);
for ( k = 0; k < col; k++)
{
for(j=0; j