4Sum

来源:互联网 发布:格力壁挂空调 r32知乎 编辑:程序博客网 时间:2024/06/05 19:31

题目描述:

Given an array S of n integers, are there elements abc, 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的解题思路可以参考:3Sum


AC代码如下:

class Solution {public:vector<vector<int>> fourSum(vector<int>& nums, int target) {vector<vector<int>> res;int numlen = nums.size();if (nums.size()<4) return res;sort(nums.begin(), nums.end());for (int i = 0; i < numlen; i++){if (i != 0 && nums[i] == nums[i - 1]) continue; //跳过重复的元素,避免结果中出现重复的四元组for (int j = i + 1; j < numlen; j++){if (j != i + 1 && nums[j] == nums[j - 1]) continue; //跳过重复的元素,避免结果中出现重复的四元组int begin = j + 1;int end = numlen - 1;while (begin < end){int sum = nums[i] + nums[j] + nums[begin] + nums[end];if (sum == target){vector<int> tmp = {nums[i],nums[j],nums[begin],nums[end]};res.push_back(tmp);while (++begin<end && nums[begin] == nums[begin - 1]); //跳过重复的元素,避免结果中出现重复的四元组while (--end>begin && nums[end] == nums[end + 1]);  //跳过重复的元素,避免结果中出现重复的四元组}else if (sum<target)begin++;elseend--;}}}return res;}};


0 0
原创粉丝点击