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: 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]]answer:class Solution {public: vector<vector<int>> fourSum(vector<int>& nums, int target) { sort(nums.begin(),nums.end()); int sum = 0; int first, second,third,forth; //int PReFirst, preSecond,preThird,preForth; vector<vector<int>> result; for(first = 0; first < nums.size(); first ++){ if(first > 0 ){ while(nums[first] == nums[first - 1]) { first ++; } } //preFirst = nums[first]; for(second = first + 1; second < nums.size(); second ++){ if(second - first > 1 ){ while(nums[second] == nums[second - 1]) { second ++; } } //preFirst = nums[first]; third = second + 1; forth = nums.size() - 1; while(third < forth){ sum = nums[first] + nums[second] + nums[third] + nums[forth]; if(sum < target) third ++; else if(sum > target) forth --; else{ vector<int> temp; temp.push_back(nums[first]); temp.push_back(nums[second]); temp.push_back(nums[third]); temp.push_back(nums[forth]); result.push_back(temp); third ++; while(nums[third] == nums[third - 1]) third ++; forth --; while(nums[forth] == nums[forth + 1]) forth --; } } } } return result; }};
新闻热点
疑难解答