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

4Sum

时间:2018-09-02 23:52:41      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:and   dup   begin   cto   nta   contain   while   size   cat   

Given an array nums of n integers and an integer target, are there elements abc, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [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]
]

 C++:

class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums,int target) {
        vector<vector<int> > result;
        if (nums.size() < 4)
            return result;
        sort(nums.begin(), nums.end());
        for (int i = 0; i < nums.size() - 3; i++){
            if (i>0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < nums.size() - 2; j++){
                if (j >i + 1 && nums[j] == nums[j - 1]) continue;
                for (int k = j + 1, m=nums.size()-1; k < m;){
                    auto sum = nums[i] + nums[j] + nums[k] + nums[m];
                    if (sum == target){
                        result.push_back(vector<int>({ nums[i], nums[j], nums[k], nums[m] }));
                        while (nums[++k] == nums[k - 1] && k < m);
                        while (nums[--m] == nums[m + 1] && k < m);
                    }
                    else if (sum < target){
                        k++;
                    }
                    else
                        m--;
                }
            }
        }
        return result;
    }
};

 

4Sum

标签:and   dup   begin   cto   nta   contain   while   size   cat   

原文地址:https://www.cnblogs.com/duan-decode/p/9575571.html

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