Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
For example, given array S = {1 0 -1 0 -2 2}, and target = 0. A solution set is: (-1, 0, 0, 1) (-2, -1, 1, 2) (-2, 0, 0, 2)
给定的n个整数数组,元素有a,b,c和d的S数组 ,满足a + b + c + d =target? 数组中查找所有唯一的四元素使之总和 等于target。
注意:
元素成套(a,b,c,d)必须满足 a<= b <= c <= d
解集必须不能重复
// // 4Sum.c // Algorithms // // Created by TTc on 15/6/15. // Copyright (c) 2015年 TTc. All rights reserved. // /** Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. */ #include "4Sum.h" #include <stdlib.h> #include <string.h> //范型法 static void swap_void(void *a,void *b,size_t size){ unsigned char *p1=(unsigned char *)a; //强制类型转换 unsigned char *p2=(unsigned char *)b; unsigned char temp; //字节型的嫁衣 while(size--){ temp=*p1; *p1=*p2; *p2=temp; p1++; p2++; } } static void tt_quick_sort( int *array, int left, int right){ if (left < right){ int t = array[(left+right)/2]; int i = left - 1; int j = right + 1; while (1){ while (array[++i] < t); while (array[--j] > t); if (i >= j){ break; } swap_void(&array[i], &array[j],sizeof(int)); } tt_quick_sort(array, left, i-1); tt_quick_sort(array, j+1, right); } } static int cmp(const int*a,const int*b){ return (*a) - (*b); } /** * Return an array of arrays of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */ int** fourSum(int* nums, int numsSize, int target, int* returnSize) { if(numsSize < 4){ return NULL; } qsort(nums, numsSize, sizeof(int), (int(*)(const void *,const void *))cmp); //tt_quick_sort(nums, 0, numsSize-1); int **result = (int **)malloc(sizeof(int*)*10000); int i,j,sum,begin,end,*temp; for(i = 0;i < numsSize - 3 ; i++){ if(i>0 && nums[i]==nums[i-1])continue; for(j = i + 1; j < numsSize - 2 ; j++){ if( j > i + 1 && nums[j] == nums[j-1])continue; begin = j + 1; end = numsSize - 1; while(begin < end){ sum = nums[i] + nums[j] + nums[begin] + nums[end]; if(sum == target){ temp = (int*)malloc(sizeof(int)*4); temp[0] = nums[i]; temp[1] = nums[j]; temp[2] = nums[begin]; temp[3] = nums[end]; result[*returnSize] = temp; (*returnSize)++; begin++; end--; while(begin<end && nums[begin]==nums[begin-1]) begin++; while(begin<end && nums[end]==nums[end+1]) end--; }else if(sum > target){ end--; while(begin < end && (nums[end] == nums[end+1])) end--; } else{ begin++; while(begin<end && (nums[begin] == nums[begin-1])) begin++; } } } } return result; } void test_fourSum(){ int nums[10] ={1, 0, -1, 0 ,-2 ,2}; int n = 6; int target = 0; int *returnSize = NULL; returnSize = (int *)malloc(sizeof(int)); int ** result = fourSum(nums, n, target, returnSize); for (int j = 0; j < *returnSize; j++) { printf("------------------\n"); for (int i = 0 ; i < 4; i++) { printf("result[%d][%d]===%d \n",j,i,result[j][i]); } } }