zoukankan      html  css  js  c++  java
  • [LeetCode] #18 4Sum

    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)

     本文如果先确定一个数,可以将问题转化为3Sum问题,3Sum问题解法如:http://www.cnblogs.com/Scorpio989/p/4440236.html

    时间:180ms。代码如下:

    class Solution {
    public:
        vector<vector<int>> fourSum(vector<int>& nums, int target) {
            vector< vector<int> > ret;
            if (nums.size() < 4)
                return ret;
            sort(nums.begin(), nums.end());
            for (size_t i = 0; i < nums.size() - 3; ++i){
                if (i != 0 && nums[i] == nums[i - 1])
                    continue;
                for (size_t j = i + 1; j < nums.size() - 2; ++j){
                    if (j != i + 1 && nums[j] == nums[j - 1])
                        continue;
                    size_t l = j + 1, k = nums.size() - 1;
                    while (l < k){
                        if (l != j + 1 && nums[l] == nums[l - 1]){
                            l++;
                            continue;
                        }
                        if (k != nums.size() - 1 && nums[k] == nums[k + 1]){
                            k--;
                            continue;
                        }
                        int sum = nums[i] + nums[j] + nums[l] + nums[k];
                        if (sum == target){
                            vector<int> v;
                            v.push_back(nums[i]);
                            v.push_back(nums[j]);
                            v.push_back(nums[l]);
                            v.push_back(nums[k]);
                            ret.push_back(v);
                            l++;
                            k--;
                        }
                        else if (sum < target)
                            l++;
                        else
                            k--;
                    }
                }
            }
            return ret;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    玩具数据库
    数据库中可能会出现的表
    SqlDbHelper
    重写 覆盖 虚方法
    页面标签的初始化
    如何将UTF8转换为UTF8n
    小软件项目开发的管理(转)
    SCRUM软件开发过程(转)
    在.Net如何制作自定义的快捷方式
    What Is a Leader
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4448862.html
Copyright © 2011-2022 走看看