leetcode-4Sum
来源:互联网 发布:手游网游 知乎 编辑:程序博客网 时间:2024/09/21 06:17
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)
bool compare(const int &a, const int &b){ return a<b;}class Solution {public: vector<vector<int> > fourSum(vector<int> &num, int target) { int n = num.size(); vector<vector<int> > ret; if(n < 4)return ret; sort(num.begin(),num.end(),compare); for(int i = 0; i < n-2; i++) { if((i > 0)&&(num[i] == num[i-1]))continue; for(int l = i+1; l < n-1; l++) { if((l > i+1)&&(num[l] == num[l-1]))continue; int a = target-num[i]-num[l]; int j = l+1; int k = n-1; while(k > j) { if(a == num[j]+num[k]) { vector<int> temp; temp.push_back(num[i]); temp.push_back(num[l]); temp.push_back(num[j]); temp.push_back(num[k]); ret.push_back(temp); k--; j++; while((num[j]==num[j-1])&&(j < n))j++; while((num[k]==num[k+1])&&(k > -1))k--; } else if(a > num[j]+num[k])j++; else k--; } } } return ret; }};
0 0
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 4 Sum
- LeetCode: 4Sum
- LeetCode 4Sum
- Leetcode: 4SUM
- 【leetcode】 4 sum
- LeetCode 4Sum
- leetcode 44: 4Sum
- [Leetcode] 4 Sum [Unsolved]
- 【leetcode】4Sum
- 数组的指针特性
- 浅谈C语言中return
- 【Codeforces Round #268 (Div. 1)】A. 24 Game【归纳法】
- 《STL源码剖析》---_auto_ptr.h阅读笔记
- DSP-BIOS使用入门
- leetcode-4Sum
- 下拉刷新 ListView
- java正则表达式用法
- CocoaPods安装和使用
- 使用Tcl脚本分配FPGA管脚
- WebCollector内核解析—如何设计一个爬虫
- Codeforces Round #269 (Div. 2) D
- leetcode - Gas Station
- matlab中关于不同包中的同名函数的调用问题