给你一个由 n 个整数组成的数组 nums ,和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] (若两个四元组元素一一对应,则认为两个四元组重复):
0 <= a, b, c, d < n
a、b、c 和 d 互不相同
nums[a] + nums[b] + nums[c] + nums[d] == target
你可以按 任意顺序 返回答案 。
示例 1:
输入:nums = [1,0,-1,0,-2,2], target = 0
输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
示例 2:
输入:nums = [2,2,2,2,2], target = 8
输出:[[2,2,2,2]]
提示:
1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
/**
* 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 **results,*columnSizes,result[4],*book;
void QuickSort(int* nums,int left,int right)
{
int i=left,j=right,temp=nums[i];
if(left>=right) return;
while(i<j)
{
while(nums[j]>=temp&&i<j) j--;
nums[i]=nums[j];
while(nums[i]<=temp&&i<j) i++;
nums[j]=nums[i];
}
nums[i]=temp;
QuickSort(nums,left,i-1);
QuickSort(nums,i+1,right);
}
bool IsExist(int *result,int *returnSize)
{
int i,j;
bool flag;
for(i=0;i<*returnSize;i++)
{
flag=true;
for(j=0;j<4;j++) if(results[i][j]!=result[j]) flag=false;
if(flag==true) return true;
}
return false;
}
void dfs(int *nums,int numsSize,long target,int step,int *returnSize,int index)
{
int i,j,temp[4],pre=-999999;
if(step==4)
{
if(target==0)
{
results[(*returnSize)]=(int *)calloc(sizeof(int),4);
for(i=0;i<4;i++) temp[i]=result[i];
QuickSort(temp,0,3);
if(IsExist(temp,returnSize)&&(*returnSize)!=0) return;
for(i=0;i<4;i++) results[(*returnSize)][i]=temp[i];
columnSizes[(*returnSize)++]=4;
}
return;
}
for(i=index;i<numsSize;i++)
{
if(nums[i]==pre) continue;
if(book[i]==0)
{
book[i]=1;
result[step]=nums[i];
pre=nums[i];
dfs(nums,numsSize,target-nums[i],step+1,returnSize,i);
book[i]=0;
}
}
}
int** fourSum(int* nums, int numsSize, int target, int* returnSize, int** returnColumnSizes){
QuickSort(nums,0,numsSize-1);
columnSizes=(int *)calloc(sizeof(int),1000);
book=(int *)calloc(sizeof(int),numsSize);
results=(int **)malloc(sizeof(int *)*1000);
*returnSize=0;
*returnColumnSizes=columnSizes;
dfs(nums,numsSize,target,0,returnSize,0);
return results;
}