The sum of eighteen Quaternions
Given a n array nums containing N integers a n d a target value, judge whether there are four elements a, b, c and D in nums, so that the value of a + b + c + d is equal to that of target? Find out all quaternions that satisfy the conditions and do not repeat.
Be careful:
The answer should not contain duplicate quaternions.
Example:
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
The set of quaternions satisfying the requirements is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
Source: LeetCode
Links: https://leetcode-cn.com/problems/4sum
Like the idea of the sum of three numbers, first sort, take out the first two traversals, then use both ends to traverse the remaining two definitions, paying attention to eliminating the situation of equality.
The sum of three links:
https://blog.csdn.net/pxh_ww/article/details/98472360
class Solution{ public: vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int> > rst; int len = nums.size(); if(len<4) return {}; sort(nums.begin(),nums.end()); for(int i=0;i<len-3;i++) { if(i>0 && nums[i]==nums[i-1]) continue; for(int j=i+1;j<len-2;j++) { if(j>i+1 && nums[j]==nums[j-1]) continue; int l = j+1, r = len-1; while(l<r) { int sum = nums[i]+nums[j]+nums[l]+nums[r]; if(sum==target) { vector<int> tmp; tmp.push_back(nums[i]); tmp.push_back(nums[j]); tmp.push_back(nums[l++]); tmp.push_back(nums[r--]); rst.push_back(tmp); while(l<r && nums[l]==nums[l-1]) l++; while(l<r && nums[r]==nums[r+1]) r--; } else if(sum>target) r--; else l++; } } } return rst; } };