/**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int cmp (const void * a, const void * b){
return ( *(int*)a - *(int*)b );
}
int** fourSum(int* nums, int numsSize, int target, int* returnSize) {
qsort(nums, numsSize, sizeof(int), cmp);
int i, j, l, r, sum;
int **res = (int**)malloc(sizeof(int*) * (numsSize * (numsSize - 1) * (numsSize - 2) * (numsSize - 3)) / 24);
//特殊情况处理
if(numsSize < 4){
*returnSize = 0;
return res;
}
//一般情况处理
*returnSize = 0;
for(i = 0; i < numsSize - 3; ++i){
//剪枝
if (i > 0 && nums[i] == nums[i-1]) continue;
if (nums[i]+nums[i+1]+nums[i+2]+nums[i+3] > target)break;
if (nums[i]+nums[numsSize-3]+nums[numsSize-2]+nums[numsSize-1] < target)continue;
for(j = i + 1; j < numsSize - 2; ++j){
//剪枝
if (j > i+1 && nums[j] == nums[j-1])continue;
if (nums[i]+nums[j]+nums[j+1]+nums[j+2] > target)break;
if (nums[i]+nums[j]+nums[numsSize-2]+nums[numsSize-1] < target)continue;
l = j + 1;
r = numsSize - 1;
while(l < r){
sum = nums[i] + nums[j] + nums[l] + nums[r];
if(sum == target){
res[*returnSize] = (int*)malloc(sizeof(int) * 4);
res[*returnSize][0] = nums[i];
res[*returnSize][1] = nums[j];
res[*returnSize][2] = nums[l];
res[*returnSize][3] = nums[r];
++(*returnSize);
do{++l;}while(nums[l] == nums[l - 1]);
do{--r;}while(nums[r] == nums[r + 1]);
}
else if(sum < target){
do{++l;}while(nums[l] == nums[l - 1]);
}
else{
do{--r;}while(nums[r] == nums[r + 1]);
}
}
}
}
return res;
}
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int cmp (const void * a, const void * b){
return ( *(int*)a - *(int*)b );
}
int** fourSum(int* nums, int numsSize, int target, int* returnSize) {
qsort(nums, numsSize, sizeof(int), cmp);
int i, j, l, r, sum;
int **res = (int**)malloc(sizeof(int*) * (numsSize * (numsSize - 1) * (numsSize - 2) * (numsSize - 3)) / 24);
//特殊情况处理
if(numsSize < 4){
*returnSize = 0;
return res;
}
//一般情况处理
*returnSize = 0;
for(i = 0; i < numsSize - 3; ++i){
//剪枝
if (i > 0 && nums[i] == nums[i-1]) continue;
if (nums[i]+nums[i+1]+nums[i+2]+nums[i+3] > target)break;
if (nums[i]+nums[numsSize-3]+nums[numsSize-2]+nums[numsSize-1] < target)continue;
for(j = i + 1; j < numsSize - 2; ++j){
//剪枝
if (j > i+1 && nums[j] == nums[j-1])continue;
if (nums[i]+nums[j]+nums[j+1]+nums[j+2] > target)break;
if (nums[i]+nums[j]+nums[numsSize-2]+nums[numsSize-1] < target)continue;
l = j + 1;
r = numsSize - 1;
while(l < r){
sum = nums[i] + nums[j] + nums[l] + nums[r];
if(sum == target){
res[*returnSize] = (int*)malloc(sizeof(int) * 4);
res[*returnSize][0] = nums[i];
res[*returnSize][1] = nums[j];
res[*returnSize][2] = nums[l];
res[*returnSize][3] = nums[r];
++(*returnSize);
do{++l;}while(nums[l] == nums[l - 1]);
do{--r;}while(nums[r] == nums[r + 1]);
}
else if(sum < target){
do{++l;}while(nums[l] == nums[l - 1]);
}
else{
do{--r;}while(nums[r] == nums[r + 1]);
}
}
}
}
return res;
}