14 - 4Sum

本文探讨了如何寻找数组中四个元素之和等于目标值的所有唯一组合。通过使用排序和双指针技巧来解决该问题,并确保解决方案集不包含重复的四元组。给出的C++实现代码详细展示了这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array S of n integers, are there elements abc, 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:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ? b ? c ? d)
  • The solution set must not contain duplicate quadruplets.

    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)



solution:  method1: 类似于3sum的方法,大概是O(n^3)时间,感觉效率有点低;想了一下没想出更优化的解法,Google了下找到一个帖子总结了k-sum问题,链接如下:

http://tech-wonderland.net/blog/summary-of-ksum-problems.html 。 递归思考的话,确实k-sum问题的求解时间为O( n^(k-1) )。

 method2: 还没想到,想到再更。


class Solution {
public:    
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<int> > res;
        int size = num.size();
        
        if(size < 4)
            return res;
            
        sort(num.begin(),num.end());
        
        for(int fir = 0; fir < size - 3; fir++)
        {
            if(num[fir] == num[fir-1] && fir != 0)
                continue;
            
            for(int sec = fir +1; sec < size - 2; sec ++)
            {
                if(num[sec] == num[sec-1] && sec != fir+1)
                    continue;
                
                int start = sec + 1;
                int end = size - 1;
                while(start < end)
                {
                    int sum = num[fir] + num[sec] + num[start] + num[end];
                    if(sum == target)
                    {
                        vector<int>tuple(4,0);
                        tuple[0] = num[fir];
                        tuple[1] = num[sec];
                        tuple[2] = num[start];
                        tuple[3] = num[end];
                        
                        res.push_back(tuple);
                        start++;
                        while(num[start] == num[start-1])
                            start++;
                        end--;
                    }
                    else if(sum < target)
                    {
                        start++;
                    }
                    else 
                    {
                        end--;
                    }
                }
                
            }
        }
        
        return res;
    }
};

实现中需注意去重。









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值