18. 4Sum
Posted hozhangel
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了18. 4Sum相关的知识,希望对你有一定的参考价值。
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] ]
找出四个数,相加等于零。
在一个列表里寻找四个数的情况,遍历方法一般为:
for(int i = 0; i < totalNum - 3; i++){ for(int m = i + 1; m < totalNum - 2 ; m++){ int j = m+1; int k = totalNum - 1; while(j<k){ //接着看情况使 j++ 或 k-- } //不想重复组合时:这里要判断num[m] 是否等于 num[m+1],等于的话m++,跳过下一个元素 } //同理,不想重复组合时:这里要判断num[i] 是否等于 num[i+1],等于的话i++,跳过下一个元素 }
和3sum closet 、 3sum 方法类似
最终提交正确的代码:
class Solution { public: vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int> > res; if(nums.size() < 4) return res; std::sort(nums.begin(), nums.end()); for (int i = 0; i < nums.size() - 3; i++) { for(int m = i + 1; m < nums.size() - 2; m ++){ int target1 = target -nums[i] - nums[m]; int front = m + 1; int back = nums.size() - 1; while (front < back) { int sum = nums[front] + nums[back]; if (sum < target1) front++; else if (sum > target1) back--; else { vector<int> triplet(4, 0); triplet[0] = nums[i]; triplet[1] = nums[m]; triplet[2] = nums[front]; triplet[3] = nums[back]; res.push_back(triplet); while (front < back && nums[front] == triplet[2]) front++; while (front < back && nums[back] == triplet[3]) back--; } } while (m + 1 < nums.size() && nums[m + 1] == nums[m]) m++; } while (i + 1 < nums.size() && nums[i + 1] == nums[i]) i++; } return res; } };
以上是关于18. 4Sum的主要内容,如果未能解决你的问题,请参考以下文章