码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode : 4Sum

时间:2015-02-14 09:51:20      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

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)

 

和2Sum,3Sum的思路基本上一样,这类问题都是先排序,然后由K Sum转换成K-1 Sum,
比如4Sum先选一个,然后从剩下的数字中求3Sum
所以问题最后还是时间复杂度的估算问题,K Sum的暴力求解是O(n ^ K)的复杂度,据说有证明最好的优化为n(n ^ k -1)所以放心大胆的一遍遍搜。。
AC代码:
class Solution {
public:
    vector<vector<int> > fourSum(vector<int> &num, int target) {
        sort(num.begin(), num.end());
        vector<vector<int>> ans;
        if(num.size() < 4){
            return ans;
        }
        for(int i = 0; i < num.size() - 3; ++i){
            if(i == 0 || num[i] != num[i - 1]){
                for(int j = i + 1; j < num.size() - 2; ++j){
                    if(j == i + 1 || num[j] != num[j - 1]){
                        int left = j + 1;
                        int right = num.size() - 1;
                        int CTarget = target - num[i] - num[j];
                        while(left < right){
                            if(num[left] + num[right] < CTarget){
                                while(left < right && num[left] == num[(left++) + 1]){ //去除重复元素,并且保证left至少会+1,除非left >= right
                                    ;
                                }
                            }else if(num[left] + num[right] > CTarget){
                                while(left < right && num[right] == num[(right--) - 1]){
                                    ;
                                }
                            }else{
                                vector<int> temp = {num[i], num[j], num[left], num[right]};
                                ans.push_back(temp);
                                while(left < right && num[right] == num[(right--) - 1]){
                                    ;
                                }
                                while(left < right && num[left] == num[(left++) + 1]){
                                    ;
                                }
                            }
                        }
                    }
                }
            }
        }

        return ans;
    }
};

 

 

leetcode : 4Sum

标签:

原文地址:http://www.cnblogs.com/64open/p/4291266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!