[LeetCode] SUM4
来源:互联网 发布:mac如何设置iphone铃声 编辑:程序博客网 时间:2024/06/07 00:23
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)
和sum3 差不多,枚举a ,b 再 解 c+d 的定值的问题。
写的时候漏了一些小地方, continue 之前要 改变p,q .
class Solution {private:vector<vector<int> > ret;public: vector<vector<int> > fourSum(vector<int> &num, int target) { // Start typing your C/C++ solution below // DO NOT write int main() functionret.clear();sort(num.begin(),num.end());for(int i = 0; i < num.size() ; i++){if( i > 0 && num[i] == num[i-1])continue;for( int j = i+1; j < num.size() ; j++){if( j > i+1 && num[j]==num[j-1])continue;int p = j + 1;int q = num.size() -1;while( p < q){if( p > j + 1 && num[p] == num[p-1]){p++;continue;}if( q < num.size() -1 && num[q] == num[q+1]){q--;continue;}int sum = num[i] + num[j] + num[p] + num[q];if(sum==target){vector<int> tmp;tmp.push_back(num[i]);tmp.push_back(num[j]);tmp.push_back(num[p]);tmp.push_back(num[q]);ret.push_back(tmp);p++;}else if(sum > target){q--;}else{p++;}}}} return ret; }};
- [LeetCode] SUM4
- 【数据结构与算法】【leetcode】sum2 sum3 sum4 Combination Sum
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- hdu 1428 优先队列广搜+记忆化搜索
- PHP5.3.5如何连接MSSql Server2005
- IE8/9下,text-indent对css描绘三角形的影响
- hadoop的常用参数
- typedef数组类型
- [LeetCode] SUM4
- 格式化数字
- C++重载运算符
- Oracle 表空间联机(online)与脱机(offline)
- [Cadence]学习笔记1——update cache的问题
- oracle表空间操作详解
- Project Euler problem 41
- makefile之编译参数
- 检测内存泄露的方法