题目:
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<vector<int> > fourSum(vector<int> &num, int target) { vector<vector<int> > 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<len-1 && num[j]==num[j+1] ) continue; int k = i+1; int z = j-1; 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-1] && k<z ) ++k; --z; while ( num[z]==num[z+1] && k<z ) --z; } else if (tmp_sum>target) { --z; while ( num[z]==num[z+1] && k<z ) --z; } else { ++k; while ( num[k]==num[k-1] && k<z ) ++k; } } } } return result; } };
Tips:
1. 上面的代码时间复杂度O(n³)并不是最优的,网上有一些其他的可能做到O(n²)用hashmap的方式。
2. 上面的代码沿用了3Sum一样的思想:
a. 3Sum需要固定一个方向的变量,头尾各设定一个指针,往中间逼近。
b. 4Sum由于多了一个变量,则需要固定头并且固定尾,在内部的头尾各设定一个指针,再往中间逼近。
3. TwoSum 3Sum 4Sum这个系列到此为止了 套路基本就是固定头或尾的变量 再往中间逼
时间: 2024-10-10 08:48:33