题目

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)

代码

class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target)
{
vector<vector<int> > result;
sort(num.begin(), num.end());
unsigned int len = num.size();
if (len<) return result;
for (int i = ; i < len-; ++i)
{
if ( i> && num[i]==num[i-] ) continue;
for (int j = len-; j>i+; --j)
{
if ( j<len- && num[j]==num[j+] ) continue;
int k = i+;
int z = j-;
while(k<z)
{
const int tmp_sum = num[i]+num[j]+num[k]+num[z];
if (tmp_sum==target)
{
vector<int> tmp;
tmp.push_back(num[i]);
tmp.push_back(num[k]);
tmp.push_back(num[z]);
tmp.push_back(num[j]);
result.push_back(tmp);
++k;
while ( num[k]==num[k-] && k<z ) ++k;
--z;
while ( num[z]==num[z+] && k<z ) --z;
}
else if (tmp_sum>target)
{
--z;
while ( num[z]==num[z+] && k<z ) --z;
}
else
{
++k;
while ( num[k]==num[k-] && k<z ) ++k;
}
}
}
}
return result;
}
};

Tips:

1. 上面的代码时间复杂度O(n³)并不是最优的,网上有一些其他的可能做到O(n²)用hashmap的方式。

2. 上面的代码沿用了3Sum一样的思想:

  a. 3Sum需要固定一个方向的变量,头尾各设定一个指针,往中间逼近。

   b. 4Sum由于多了一个变量,则需要固定头并且固定尾,在内部的头尾各设定一个指针,再往中间逼近。

3. TwoSum 3Sum 4Sum这个系列到此为止了 套路基本就是固定头或尾的变量 再往中间逼

=================================================

第二次过这个题目,一开始想到了要固定头尾的思路,再在中间采用2Sum的算法。两个原因没有成行:

1. 看到了O(n³)超时的说法,没敢写。。。

2. 可能是第一次AC就是学的这种写法,有印象

但是,第二次AC代码并不是上述的思路,而是采用了一种类似万能的写法。

class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int> > ret;
if ( nums.size()< ) return ret;
vector<int> tmp;
std::sort(nums.begin(), nums.end());
for ( int i=; i<nums.size()-; ++i )
{
if ( i> && nums[i]==nums[i-] ) continue;
for ( int j=i+; j<nums.size()-; ++j )
{
if ( j>i+ && nums[j]==nums[j-]) continue;
int begin = j+;
int end = nums.size()-;
while ( begin<end )
{
int value = nums[i]+nums[j]+nums[begin]+nums[end];
if ( value<target )
{
begin++;
}
else if ( value>target )
{
end--;
}
else
{
tmp.push_back(nums[i]);
tmp.push_back(nums[j]);
tmp.push_back(nums[begin]);
tmp.push_back(nums[end]);
ret.push_back(tmp);
tmp.clear();
begin++;
while ( begin<end && nums[begin]==nums[begin-] ) begin++;
end--;
while ( begin<end && nums[end]==nums[end+] ) end--;
}
}
}
}
return ret;
}
};

tips:

还是学习的这个blog的思路:http://www.cnblogs.com/tenosdoit/p/3649607.html

1. 先固定一个元素i

2. 再从i+1往后遍历,每次固定一个元素j

3. 固定完j之后,就可以变成了两边夹逼的问题了。

这种思路是我见过思路最清晰的。

【4Sum】cpp的更多相关文章

  1. 【Permutations】cpp

    题目: Given a collection of numbers, return all possible permutations. For example,[1,2,3] have the fo ...

  2. 【Subsets】cpp

    题目: Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset ...

  3. 【Anagrams】 cpp

    题目: Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will ...

  4. 蓝桥杯 【dp?】.cpp

    题意: 给出一个2*n的方格,当刷完某一个方格的漆后可以且只可以走到相邻的任何一格,即上 下 左 右 左上 左下 右上 右下.可以从任意一个格子开始刷墙,问有多少种刷法,因为随着n的增大方案数会变多, ...

  5. 【Triangle 】cpp

    题目: Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjace ...

  6. 【N-Queens】cpp

    题目: The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two que ...

  7. 【Combinations】cpp

    题目: Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For ex ...

  8. 【Candy】cpp

    题目: There are N children standing in a line. Each child is assigned a rating value. You are giving c ...

  9. 【3Sum】cpp

    题目: Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find al ...

随机推荐

  1. Python高效开发实战——Django、Tornado、Flask、Twisted

    今天要推荐的就是这本书,内容涉及四种主流的Python Web开发框架,零基础完成网站搭建.数据库设计.前后端开发,全方位领悟Python原理与应用. 最新最全的框架实战,尽在这本书,可搜索亚马逊.京 ...

  2. sql优化经典例子

    场景 我用的数据库是mysql5.6,下面简单的介绍下场景 课程表 create table Course( c_id int PRIMARY KEY, name varchar(10) ) 数据10 ...

  3. php:生成的时间与本地电脑的时间不匹配

    如题,在php中我发现在数据库中的时间跟电脑上的时间没有同步 本地时间: 数据库中,生成的时间: 很明显,时分秒是对应不上去的,那么我们只要在php.ini中找到 这里被注释掉了,那我们就改成这样: ...

  4. [UIImage imageWithContentsOfFile:@""] 内存警告

    You will want to use the [UIImage imageWithContentsOfFile:@""] method, as that doesn't cac ...

  5. python_21_copy

    import copy person=['name',['saving',100]] #3种浅copy方式 p1=copy.copy(person) p2=person[:] p3=list(pers ...

  6. Andrew NG 自动化所演讲(20140707):DeepLearning Overview and Trends

    出处 以下内容转载于 网友 Fiona Duan,感谢作者分享 (原作的图片显示有问题,所以我从别处找了一些附上,小伙伴们可以看看).最近越来越觉得人工智能,深度学习是一个很好的发展方向,应该也是未来 ...

  7. IPV6验证正则表达式

    验证ipv6的正则表达式: 例:fe80::ec61:c1d1:9827:82be%13 \s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9 ...

  8. 第十二篇、OC_仿淘宝商品详情页的翻页

    // // GFBProductViewController.m // elmsc // // Created by MAC on 2016/11/26. // Copyright © 2016年 G ...

  9. php 递归

    function digui($data,$j=0,$lev=0){ $subs=array();//存放子孙数组 foreach ($data as $v){ if ($v['parent_id'] ...

  10. html +css 登陆框中加用户图片,并设置登陆名不盖住图标

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...