题目描述
给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。
满足要求的四元组集合为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
白话题目:
还记得第15题三数之和,16题最接近的三数之和不?这回数组还是那个类似的数组+目标值。找出所有不重复元素的四元组而已。
算法:
有了之前的基础,这个题就没有那么难了。之前是一个i,现在假想固定i,j移动L,R,双指针。
根据nums[i]+nums[j]+nums[L],nums[R]的值移动指针。
记得去重复啊。
详细解释关注 B站 【C语言全代码】学渣带你刷Leetcode 不走丢 https://www.bilibili.com/video/BV1C7411y7gB
C语言完全代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//声明排序为整型数组递增
/**
* 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 comp(const void *a,const void *b)
{
return *(int*)a-*(int*)b;
}
int** fourSum(int* nums, int numsSize, int target, int* returnSize, int** returnColumnSizes)
{
int** returnArray = (int**)malloc(sizeof(int*) * (numsSize)*(numsSize)); //Cn3就够了
if(numsSize<4)
{
return NULL;
}
qsort(nums,numsSize,sizeof(int),comp); //快速排序 升序
//int **ans=(int **)malloc(sizeof(int *)*numsSize*6);
int i,j,L,R;
*returnColumnSizes =(int *)malloc(sizeof(int) *numsSize*numsSize);
*returnSize=0;
for(i=0; i<numsSize-3; i++)
{
if (i>0&&nums[i]==nums[i-1])//i去重
continue;
for(j=i+1; j<numsSize-2; j++)
{
if (j>i+1&&nums[j]==nums[j-1])//j去重
continue;
L=j+1;
R=numsSize-1;
while(L<R)
{
int main()
{
printf("测试数据的个数 6\n");
int numsSize;
scanf("%d",&numsSize);
int nums[numsSize];
int i,j;
printf("测试数据 1, 0, -1, 0, -2, 2\n");
for(i=0; i<numsSize; i++)
{
scanf("%d",&nums[i]);
}
printf("请输入目标值target:\n");
int target;
scanf("%d",&target);
int returnSize=0;
int **returnColumnSizes =(int**)malloc(sizeof(int*)*numsSize);//
int **resultArray=fourSum( nums, numsSize, target, &returnSize, returnColumnSizes);
printf("%d\n",returnSize);
for(i=0; i<returnSize; i++)
{
for ( j = 0; j < (*returnColumnSizes)[i]; j ++)
{
printf("%d ",resultArray[i][j]) ;
}
printf("\n");
}
return 0;
}