回溯写了个超时了。这里写得树层去重还是值得借鉴得。
/**
* 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 temp[3]={0};
void dfs(int** array,int* nums,int numsSize,int* returnSize,int* column,int index,int count,int sum){
if(count>3 || (index>=numsSize && count!=3)) return;
if(count==3&&sum!=0) return;
if(count==3 && sum==0){
column[*returnSize]=3;
array[*returnSize]=(int*)malloc(sizeof(int)*3);
for(int i=0;i<3;i++) array[*returnSize][i]=temp[i];
(*returnSize)++;
return;
}
if(sum>0 && nums[index]>0) return;
for(int i=index;i<numsSize;i++){
if(i==index||(nums[i]!=nums[i-1])){
temp[count]=nums[i];
dfs(array,nums,numsSize,returnSize,column,i+1,count+1,sum+nums[i]);
}
}
}
int cmp(const void* a,const void* b){
return *(int*)a-*(int*)b;
}
int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
qsort(nums,numsSize,sizeof(int),cmp);
int* column=(int*)malloc(sizeof(int)*3500);
*returnSize=0;
int** array=(int**)malloc(sizeof(int*)*3500);
dfs(array,nums,numsSize,returnSize,column,0,0,0);
*returnColumnSizes=column;
return array;
}
结果:
标签:count,index,15,returnSize,int,三数,&&,array From: https://www.cnblogs.com/llllmz/p/18068736