[LeetCode] 4Sum
时间:2014-04-29 22:40:00
收藏:0
阅读:438
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)
这题各种面熟,先来暴力的吧。因为要求abcd是递增的,所以可以先将num排序以后再爆,嗯。
我擦咧闹不住暴破法(Time Limit Exceed):
1 vector<vector<int> > fourSum(vector<int> &num, int target) { 2 vector<vector<int>>result; 3 if (num.size() < 4) return result; 4 sort(num.begin(), num.end()); 5 for (int i=0; i<num.size()-3; i++){ 6 for (int j=i+1; j<num.size()-2; j++){ 7 for (int k=j+1; k<num.size()-1; k++){ 8 for (int v=k+1; v<num.size(); v++){ 9 if (num[i]+num[j]+num[k]+num[v] == target){ 10 vector<int>tmp; 11 tmp.push_back(num[i]); 12 tmp.push_back(num[j]); 13 tmp.push_back(num[k]); 14 tmp.push_back(num[v]); 15 result.push_back(tmp); 16 } 17 } 18 } 19 } 20 } 21 return result; 22 }
O(n^4)就是个娱乐,别说大集合没戏,连稍微大一点的集合都过不了的。
看看优化,可以把最后一层循环n变成logn, 思想是最后一层循环实际上是为了从 [k+1, num.size()) 中找到一个数x且x=target -
(num[i]+num[j]+num[k]) 。这样我们就可以用二分查找代替遍历,所以原本的O(n^4)就变成了O(n^3
logn)
复杂度依然是难以接受的,但至少比n^4要好一丢丢,期待进一步优化...
我擦咧稍微闹得住一丢丢暴破法(Time Limit Exceed):
1 vector<vector<int> > fourSum(vector<int> &num, int target) { 2 vector<vector<int>>result; 3 if (num.size() < 4) return result; 4 sort(num.begin(), num.end()); 5 for (int i=0; i<num.size()-3; i++){ 6 for (int j=i+1; j<num.size()-2; j++){ 7 for (int k=j+1; k<num.size()-1; k++){ 8 if (binary_search(num.begin()+k+1, num.end(), target - num[i]-num[j]-num[k])){ 9 vector<int>tmp; 10 tmp.push_back(num[i]); 11 tmp.push_back(num[j]); 12 tmp.push_back(num[k]); 13 tmp.push_back(target - num[i]-num[j]-num[k]); 14 result.push_back(tmp); 15 } 16 } 17 } 18 } 19 return result; 20 }
TO BE CONTINUE....
评论(0)