题目:
Given an array S of n integers, are there elements a, b, c, 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 > fourSum(vector &num, int target) { vector > result; sort(num.begin(), num.end()); unsigned int len = num.size(); if (len<4) return result; for (int i = 0; i < len-3; ++i) { if ( i>0 && num[i]==num[i-1] ) continue; for (int j = len-1; j>i+2; --j) { if ( j
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-1] && k
target) { --z; while ( num[z]==num[z+1] && k 1. 上面的代码时间复杂度O(n³)并不是最优的,网上有一些其他的可能做到O(n²)用hashmap的方式。
2. 上面的代码沿用了3Sum一样的思想:
a. 3Sum需要固定一个方向的变量,头尾各设定一个指针,往中间逼近。
b. 4Sum由于多了一个变量,则需要固定头并且固定尾,在内部的头尾各设定一个指针,再往中间逼近。
3. TwoSum 3Sum 4Sum这个系列到此为止了 套路基本就是固定头或尾的变量 再往中间逼
1. 看到了O(n³)超时的说法,没敢写。。。
2. 可能是第一次AC就是学的这种写法,有印象
class Solution {public: vector > fourSum(vector & nums, int target) { vector > ret; if ( nums.size()<4 ) return ret; vector tmp; std::sort(nums.begin(), nums.end()); for ( int i=0; i 0 && nums[i]==nums[i-1] ) continue; for ( int j=i+1; j i+1 && nums[j]==nums[j-1]) continue; int begin = j+1; int end = nums.size()-1; while ( begin 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
1. 先固定一个元素i
2. 再从i+1往后遍历,每次固定一个元素j
3. 固定完j之后,就可以变成了两边夹逼的问题了。