标签:leetcode
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:
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) 解题思路: 由于最终结果集中的四元组是非降序的,所以事先对序列进行排序,然后分别枚举c,d的位置. 去重的做法与3Sum的做法类似,只是多了一重循环.时间复杂度为O(N^3). 解题代码:class Solution { public: vector<vector<int> > fourSum(vector<int> &num, int target) { sort(num.begin(),num.end()); vector<vector<int> > res; int n = num.size() , arr[4] ; bool flag = false; for(int d = n - 1 ; d > 2 ; --d) { if( d < n - 1 && num[d] == num[d+1]) continue; for(int c = d - 1 ; c > 1 ; --c) { if( c < d - 1 && num[c] == num[c+1]) continue; int a = 0 , b = c - 1 ; while( a < b) { long long sum = num[a] + num[b] + num[c] + num[d] ; if(sum == target) { if(!flag) { arr[0] = num[a] , arr[1] = num[b] , arr[2] = num[c] , arr[3] = num[d]; res.push_back(vector<int>(arr,arr+4)); flag = true; } else if(arr[0] != num[a] || arr[1] != num[b] || arr[2] != num[c] || arr[3] != num[d]) { arr[0] = num[a] , arr[1] = num[b] , arr[2] = num[c] , arr[3] = num[d]; res.push_back(vector<int>(arr,arr+4)); } ++a , --b ; continue; } sum > target ? --b : ++a ; } } } return res; } };
标签:leetcode
原文地址:http://blog.csdn.net/dream_you_to_life/article/details/27214191