标签:
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)
class Solution { public: vector<vector<int> > fourSum(vector<int> &num, int target) { sort(num.begin(), num.end()); vector<vector<int>> ans; if(num.size() < 4){ return ans; } for(int i = 0; i < num.size() - 3; ++i){ if(i == 0 || num[i] != num[i - 1]){ for(int j = i + 1; j < num.size() - 2; ++j){ if(j == i + 1 || num[j] != num[j - 1]){ int left = j + 1; int right = num.size() - 1; int CTarget = target - num[i] - num[j]; while(left < right){ if(num[left] + num[right] < CTarget){ while(left < right && num[left] == num[(left++) + 1]){ //去除重复元素,并且保证left至少会+1,除非left >= right ; } }else if(num[left] + num[right] > CTarget){ while(left < right && num[right] == num[(right--) - 1]){ ; } }else{ vector<int> temp = {num[i], num[j], num[left], num[right]}; ans.push_back(temp); while(left < right && num[right] == num[(right--) - 1]){ ; } while(left < right && num[left] == num[(left++) + 1]){ ; } } } } } } } return ans; } };
标签:
原文地址:http://www.cnblogs.com/64open/p/4291266.html