zoukankan      html  css  js  c++  java
  • [Leetcode 48] 18 4 Sum

    Problem:

    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)

    Analysis:

    It's very much like 3 Sum except that we need another variable start from the end of the given array

    Code:

     1 class Solution {
     2 public:
     3     vector<vector<int> > fourSum(vector<int> &num, int target) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         vector<vector<int> > res;
     7         
     8         sort(num.begin(), num.end());
     9         
    10         int a = 0;
    11         while (a < num.size()) {
    12             int b = num.size()-1;
    13             while (b > a) {
    14                 int c = a+1, d = b-1;
    15                 
    16                 while (c < d) {
    17                     int sum = num[a] + num[b] + num[c] + num[d];
    18                 
    19                     if (sum == target) {
    20                         vector<int> tmp;
    21                         tmp.push_back(num[a]);
    22                         tmp.push_back(num[c]);
    23                         tmp.push_back(num[d]);
    24                         tmp.push_back(num[b]);
    25                     
    26                         res.push_back(tmp);
    27                     
    28                         do {c++;} while (num[c]==num[c-1] && c < b);
    29                         do {d--;} while (num[d]==num[d+1] && d > a);
    30                     } else if ( sum < target) {
    31                         c++;
    32                     } else {
    33                         d--;
    34                     }
    35                 }
    36                 
    37                 do {b--;} while (num[b] == num[b+1] && b > 0);
    38             }
    39             
    40             do {a++;} while (num[a] == num[a-1] && a < num.size());
    41         }
    42         
    43         return res;
    44     }
    45 };
    View Code

    Attention:

  • 相关阅读:
    前端通过Nginx反向代理解决跨域问题
    SpringMVC解决跨域问题
    SpringMVC空字符串转为null
    什么是优秀的程序员
    Windows下Nginx实现负载均衡
    SpringMVC实现PUT请求上传文件
    设计模式解密(6)
    设计模式解密(5)- 外观模式(门面模式)
    设计模式解密(4)- 模板方法模式
    eclipse上传新项目到GitHub
  • 原文地址:https://www.cnblogs.com/freeneng/p/3098449.html
Copyright © 2011-2022 走看看