本文共 1289 字,大约阅读时间需要 4 分钟。
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]]
这道题中需要的是在一个数组中需找四个数字使得他们的和等于目标值。这道题相比于之前的问题其实是一样的,我们可以套用3Sum的思路来解题。这里可以将目标值减去第一个数,那么这样的情况就变成了3Sum问题了。
class Solution {public: vector> fourSum(vector & nums, int target) { int len(nums.size()); vector > value; sort(nums.begin(), nums.end()); if(len < 4) return value; if(nums[0]==nums[len-1] && 4==len && target==nums[0]*4) { value.push_back(nums); return value; } int left(0), right(0); for(int i=0; i 0 && nums[i]==nums[i-1]) continue; for(int k=i+1; k i+1 && nums[k]==nums[k-1]) continue; int temp = target - nums[i] - nums[k]; int left = k+1; int right = len-1; while(left
转载地址:http://efkhj.baihongyu.com/