78. Subsets【leetcode】for循环内部和外部的输出的数据不一致,求点拨

使用二进制的方法来解这个问题。但是在subset函数内部,for循环里边,单步输出中间结果是没问题的,但在所有的子集都生成之后,再次输出,结果是不一样的,而且出现了乱码的情况。
测试为{1,2,3,5}
图片描述

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <math.h>

#include <limits.h>

int cmpfunc (const void * a, const void * b){

return ( *(int*)a - *(int*)b );

}

int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) {

int size = 1 << numsSize;

int** rst = (int**)malloc(sizeof(int *) * size);

memset(rst,0,sizeof(rst));

for(int i = 0; i < size; i++) {

rst[i] = (int*)malloc(sizeof(int)*numsSize);

memset(rst[i], 0, sizeof(rst[i]));

}

qsort( nums, numsSize, sizeof(int), cmpfunc);

for (int i = 0; i < size; i++) {

int len = 0;

int tmp = i;

for (int j = 0; (j < numsSize) && tmp; j++) {

if (tmp & 1) {

rst[i][len++] = nums[j];

}

tmp >>= 1;

}

for(int j = 0; j<len;j++) //{}

printf("%10d",rst[i][j]);

printf("\n");

columnSizes[i] = (int*)malloc(sizeof(int));

*columnSizes[i] = len;

}

for(int i = 0; i<size;i++){

for(int j = 0; j<*columnSizes[i];j++) //{}

printf("%10d",rst[i][j]);

printf("\n");

}

*returnSize = size;

return rst;

}

int main(){

int nums[] = {1,2,3,5};

int numsSize =4;

int* size = (int*)malloc(sizeof(int));

*size = 0;

int** columnSizes = (int **)malloc(sizeof(int *));

int** rst1 = (int **)malloc(sizeof(int*)*numsSize);

memset(rst1,0,sizeof(rst1));

rst1 = subsets(nums,numsSize,columnSizes,size);

int len = 1 << numsSize;;

printf("%5d\n",*size);

for (int i = 0; i < *size; i++) {

//printf("1");

for (int j = 0; j < *columnSizes[i]; j++) {

// printf("%5d",rst[i][j]);

}

//free(rst[i]);

// printf("\n");

}

//free(rst);

// printf("%5d\n",a);

system("pause");

return 0;

}

回答:

自己写了一下, 通过了leetcode. 供参考.

static int cmpfunc (const void* a, const void* b) {

return *(int*)a - *(int*)b;

}

int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) {

int i, j, size, tsize;

int *colSizeArr, *tArr;

int **subsetpp;

subsetpp = NULL;

tArr = (int *)malloc(sizeof(int) * numsSize);

if (!tArr)

goto err;

size = (1 << numsSize);

*returnSize = size;

colSizeArr = (int *)malloc(sizeof(int) * size);

if (!colSizeArr)

goto err;

subsetpp = (int **)calloc(size, sizeof(int*));

if (!subsetpp)

goto err;

for (i = 0; i < size; i++) {

for (tsize = j = 0; j < numsSize; j++)

if (i & (1 << j))

tArr[tsize++] = nums[j];

subsetpp[i] = (int *)malloc(sizeof(int) * tsize);

if (!subsetpp[i])

goto err;

qsort(tArr, tsize, sizeof(int), cmpfunc);

memcpy(subsetpp[i], tArr, sizeof(int) * tsize);

colSizeArr[i] = tsize;

}

free(tArr);

*columnSizes = colSizeArr;

return subsetpp;

err:

for (i = 0; i < size; i++)

if (subsetpp[i])

free(subsetpp[i]);

if (subsetpp)

free(subsetpp);

if (colSizeArr)

free(colSizeArr);

if (tArr)

free(tArr);

return NULL;

}

以上是 78. Subsets【leetcode】for循环内部和外部的输出的数据不一致,求点拨 的全部内容, 来源链接: utcz.com/p/195815.html

回到顶部