4Sum
来源:互联网 发布:淘宝购物车怎么分享 编辑:程序博客网 时间:2024/04/28 05:06
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)
class Solution {public: vector<vector<int> > fourSum(vector<int> &num, int target) { vector<vector<int> >result; vector<int>tmp; int sum = num.size(); if(sum < 4){ return result; } sort(num.begin(),num.end()); for(int i = 0; i < num.size() - 3; i++){ if(i > 0 && num[i] == num[i - 1]){ continue; } for(int j = i + 1; j < num.size() - 2; j++){ if(j > i + 1 && num[j] == num[j - 1]){ continue; } int m = j + 1; int n = num.size() - 1; while(m < n){ if(m > j + 1 && num[m] == num[m - 1]){ m++; continue; } if(n < num.size() - 1 && num[n] == num[n + 1]){ n--; continue; } int temp = num[i] + num[j] + num[m] + num[n]; if(temp > target){ n--; } else if(temp < target){ m++; } else{ tmp.clear(); tmp.push_back(num[i]); tmp.push_back(num[j]); tmp.push_back(num[m]); tmp.push_back(num[n]); result.push_back(tmp); m++; n--; } } } } return result; }};
0 0
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- 3Sum 3Sum Closest 4Sum
- 3Sum & 3Sum Closest & 4Sum
- 2Sum 3Sum 4Sum
- 3sum、3Sum closet、 4sum
- 3Sum, 3Sum Closest, 4 Sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 4Sum
- 在C++程序中调用被C编译器编译后的函数为什么要加extern “C”
- mysql 索引
- android学习日志02__HelloWorld 和 程序目录结构
- 如何使用Log4j?
- DEDE全局变量再次覆盖研究
- 4Sum
- 美轮美奂的phonegap(七)---系统事件的注册
- Objective-C: difference between id and void *
- 【练习题】编写打印出一个单链表的所有元素的程序【链表】
- SQL 数据库中的存储过程的参数问题(case when)
- ZooKeeper典型应用场景一览
- 使用Android application测试API
- u-boot编写记录(第一阶段)
- Please use the /MD switch for _AFXDLL builds的错误