C solution for those who wanna brush up memory allocation skills


  • 0
    C
    int cmpfunc (const void * a, const void * b)
    {
       return ( *(int*)a - *(int*)b );
    }
     
    int findTrailingZeros(int num){
        int ret=0;
        while((num&1)==0){
            ret++;
            num=num>>1;
        }
        return ret;
    } 
    
    int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) {
    	if (nums == NULL || numsSize == 0) return NULL;
    	*returnSize = 0;
    
    	int* nums1 = (int*)malloc(sizeof(int)*numsSize);
    	//int* nums1= (int*)calloc(numsSize, sizeof(int));
    	memcpy(nums1, nums, sizeof(int)*numsSize);
    
    	qsort(nums1, numsSize, sizeof(int), cmpfunc);
    
    	int numOfComb = 1 << numsSize;
    	*returnSize = numOfComb;
    	int **result = (int**)calloc(*returnSize, sizeof(int*));
    	*columnSizes = (int*)calloc(*returnSize, sizeof(int));
    
    	int perResultBank[100];
    	memset(perResultBank, 0, sizeof(int)* 100);
    
    	for (int i = 0; i<numOfComb; i++){
    		long temp = i;
    		int perResultSize = 0;
    		while (temp != 0){
    			int indexOfLast1 = findTrailingZeros(temp);
    			perResultBank[perResultSize] = nums1[indexOfLast1];
    			perResultSize++;
    			temp &= (temp - 1);
    		}
    		result[i] = (int*)calloc(perResultSize,sizeof(int));
    		memcpy(result[i], perResultBank, sizeof(int)*perResultSize);
    		(*columnSizes)[i] = perResultSize;
    	}
    	return result;
    }

Log in to reply
 

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