Leetcode 46. Permutations with C

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;
    
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值