标签:
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)
此题和3sum思路基本相同,不同的是,需要固定两个数,而不是一个数,而且要求4个数的和是target而不是0。
class Solution { private: vector<vector<int>> result; public: vector<vector<int>> fourSum(vector<int>& nums, int target) { if(nums.size()<4) return result; sort(nums.begin(),nums.end()); vector<int> temp(4); for(int i=0;i<nums.size()-3;i++){ if(i!=0&&nums[i]==nums[i-1]) continue; for(int j=i+1;j<nums.size()-2;j++){ if(j!=i+1&&nums[j]==nums[j-1]) continue; int left=j+1; int right=nums.size()-1; while(left<right){ int sum=nums[i]+nums[j]+nums[left]+nums[right]; if(sum==target){ temp[0]=nums[i]; temp[1]=nums[j]; temp[2]=nums[left]; temp[3]=nums[right]; result.push_back(temp); left++; right--; while(left<right&&nums[left]==nums[left-1]) left++; while(left<right&&nums[right]==nums[right+1]) right--; } else if(sum>target) right--; else left++; } } } return result; } };
标签:
原文地址:http://www.cnblogs.com/zhoudayang/p/5114415.html