学渣带你刷Leetcode0047全排列 II 

题目描述

给定一个可包含重复数字的序列,返回所有不重复的全排列。

示例:

输入: [1,1,2]
输出:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

白话题目:

和四十六好像啊,不过这里面有重复的数据。

算法:

剑走偏锋,利用46题,直接去重复吧   

1 1 2;1 2 1;2 1 1----》 1 1 2;1 2 1;2 1 1

详细解释关注 B站  【C语言全代码】学渣带你刷Leetcode 不走丢 https://www.bilibili.com/video/BV1C7411y7gB

C语言完全代码

#include <stdio.h>
#include <stdlib.h>
#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<end)
    {
        temp = nums[begin];
        nums[begin] = nums[end];
        nums[end] = temp;
        begin++;
        end--;
    }
}

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

void nextPermutation(int* nums, int numsSize)
{
    int i = numsSize-2;

    while (i >= 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** permuteUnique(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<numsSize; j++)
        {
            ret_array[k][j] =nums[j];
        }
        col_size[k]=numsSize;
        nextPermutation(nums, numsSize);

         int flag=0;
         int k;
         for(k=0; k<numsSize; k++)
        {
           if( !(ret_array[0][k] ==nums[k]))
           {
               flag=1;
               break;
           }
        }
        printf("\n");
        if(flag==0)
        {

            break;
        }
    }
    //printf("%d",col);

    //3. 返回题目所求
    *returnSize = k+1;
    *returnColumnSizes = col_size;

    return ret_array;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值