【C】a simple recursion solution


  • 0
    G
    int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize)
    {
        int i,j,preSize,curSize,preLen;
        int **subSets;
        int **preSubSets;
        int *tempSet;
        if(numsSize==0)
        {
            subSets=(int **)malloc(sizeof(int *));
            subSets[0]=NULL;
            (*columnSizes)=(int *)malloc(sizeof(int));
            (*columnSizes)[0]=0;
            *returnSize=1;
            return subSets;
        }
        preSubSets=subsets(nums,numsSize-1,columnSizes,returnSize);
        preSize=(*returnSize);
        (*returnSize)*=2;
        curSize=(*returnSize);
        subSets=(int **)realloc(preSubSets,curSize*sizeof(int *));
        (*columnSizes)=(int *)realloc((*columnSizes),curSize*sizeof(int));
        for(i=0;i<preSize;i++)
        {
            preLen=(*columnSizes)[i];
            tempSet=(int *)malloc((preLen+1)*sizeof(int));
            for(j=0;j<preLen;j++)
            {
                tempSet[j]=subSets[i][j];
            }
            tempSet[preLen]=nums[numsSize-1];
            subSets[preSize+i]=tempSet;
            (*columnSizes)[preSize+i]=preLen+1;
        }
    
        return subSets;
    
    }
    

    it may be dangerous with too much realloc.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.