【题目】
4Sum
Total Accepted: 3493 Total
Submissions: 16137My Submissions
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:
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- 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)
【题意】
给定n个整数的数组S,是否在 数组S中有元素a,b,c,d,使得a + b + c + d = target?在数组中找出独一无二的四元素组,使得他们之和为target。
注意:
在四元素组(a,b,c,d)中,必须满足非递减排序。 (即a≤b≤c≤d)
该解决方案集中一定不能包含重复的四元素组。
【分析】
- 对数组排序
- 确定四元数中的前两个(a,b)
- 遍历剩余数组确定两外两个(c,d),确定cd时思路跟3Sum确定后两个数据一样,二分查找左右逼近。
- 在去重时采用set集合
【代码】
/********************************* * 日期:2014-01-18 * 作者:SJF0115 * 题号: 4Sum * 来源:http://oj.leetcode.com/problems/4sum/ * 结果:AC * 来源:LeetCode * 总结: **********************************/ #include <iostream> #include <stdio.h> #include <vector> #include <set> #include <algorithm> using namespace std; class Solution { public: vector<vector<int> > fourSum(vector<int> &num, int target) { int i,j,start,end; int Len = num.size(); vector<int> triplet; vector<vector<int>> triplets; set<vector<int>> sets; //排序 sort(num.begin(),num.end()); for(i = 0;i < Len-3;i++){ for(j = i + 1;j < Len - 2;j++){ //二分查找 start = j + 1; end = Len - 1; while(start < end){ int curSum = num[i] + num[j] + num[start] + num[end]; //相等 -> 目标 if(target == curSum){ triplet.clear(); triplet.push_back(num[i]); triplet.push_back(num[j]); triplet.push_back(num[start]); triplet.push_back(num[end]); sets.insert(triplet); start ++; end --; } //大于 -> 当前值小需要增大 else if(target > curSum){ start ++; } //小于 -> 当前值大需要减小 else{ end --; } }//while } }//for //利用set去重 set<vector<int>>::iterator it = sets.begin(); for(; it != sets.end(); it++) triplets.push_back(*it); return triplets; } }; int main() { vector<vector<int>> result; Solution solution; vector<int> vec; vec.push_back(-3); vec.push_back(-2); vec.push_back(-1); vec.push_back(0); vec.push_back(0); vec.push_back(1); vec.push_back(2); vec.push_back(3); result = solution.fourSum(vec,0); for(int i = 0;i < result.size();i++){ for(int j = 0;j < result[i].size();j++){ printf("%d ",result[i][j]); } printf("\n"); } return 0; }
【测试】
Input: | [-1,0,1,2,-1,-4], -1 |
Expected: | [[-4,0,1,2],[-1,-1,0,1]] |
Input: | [-3,-2,-1,0,0,1,2,3], 0 |
Expected: | [[-3,-2,2,3],[-3,-1,1,3],[-3,0,0,3],[-3,0,1,2],[-2,-1,0,3],[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]] |
时间: 2025-01-26 07:11:13