很好的题目,使我的大脑旋转。
/**
* 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[40];
int visit[101];
int cmp(const void* a,const void* b){
return *(int*)a-*(int*)b;
}
void dfs(int* candidates,int candidatesSize,int target,int** array,int* returnSize,int *column,int now,int index,int n){
if(now>target) return;
if(now==target){
column[*returnSize]=n;
array[*returnSize]=(int*)malloc(sizeof(int)*n);
for(int i=0;i<n;i++) array[*returnSize][i]=temp[i];
(*returnSize)++;
return;
}
for(int i=index;i<candidatesSize;i++){
if(i!=0&&candidates[i]==candidates[i-1]&&visit[i-1]==0) continue;
temp[n]=candidates[i];
visit[i]=1;
dfs(candidates,candidatesSize,target,array,returnSize,column,now+temp[n],i+1,n+1);
visit[i]=0;
}
}
int** combinationSum2(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes) {
qsort(candidates,candidatesSize,sizeof(int),cmp);
*returnSize=0;
int* column=(int*)malloc(sizeof(int)*200);
int** array=(int**)malloc(sizeof(int*)*200);
for(int i=0;i<101;i++) visit[i]=0;
dfs(candidates,candidatesSize,target,array,returnSize,column,0,0,0);
*returnColumnSizes=column;
return array;
}
结果:
标签:returnSize,int,void,40,IIc,array,now,总和 From: https://www.cnblogs.com/llllmz/p/18061614