LeetCode 18. 4Sum
2016-05-16 07:15
344 查看
#include <iostream> #include <vector> #include <algorithm> using namespace std; /* Given an array S of n integers, are there elements a, b, c and d such that a + b + c +d = target ? Find all unique quadruplets in the array which gives the sum of target. Note: 1: Elements in quadruplet(a, b, c d) must be in non-descending order (ie, a <= b <= c <= d) 2: 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} */ // Time Complexity O(N^3) vector< vector<int> > FourSum(vector<int>& nums, int target) { if(nums.size() < 4) return {}; vector< vector<int> > res; sort(nums.begin(), nums.end()); for(int i = 0; i < nums.size() - 3; ++i) { for(int j = i + 1; j < nums.size() - 2; ++j) { int start = j + 1; int end = nums.size() - 1; while(start < end) { int sum = nums[i] + nums[j] + nums[start] + nums[end]; if(sum == target) { vector<int> tmp; tmp.push_back(nums[i]); tmp.push_back(nums[j]); tmp.push_back(nums[start]); tmp.push_back(nums[end]); res.push_back(tmp); start++; --end; } else if(sum < target) start++; else end--; } } } sort(res.begin(), res.end()); res.resize(unique(res.begin(), res.end()) - res.begin()); return res; } int main(void) { vector<int> nums{1, 1, 1, 1, 1}; vector< vector<int> > res = FourSum(nums, 4); for(int i = 0; i < res.size(); ++i) { for(int j = 0; j < res[i].size(); ++j) { cout << res[i][j] << " "; } cout << endl; } }
相关文章推荐
- Java实现HTML代码生成PDF文档
- Java实现HTML代码生成PDF文档
- 你真的了解load方法么?
- 战略转移, 各位zhihu见
- Spring学习(一)---IoC介绍
- iOS雷达图 iOS RadarChart实现
- Thinking in java并发
- Android获取Manifest中<meta-data>元素的值
- 布局
- PAT-Java-1017. A除以B (20)
- Spring学习(一)---IoC介绍
- View的滑动冲突问题
- RHEL7.0 ssh免密码登录
- 【华为OJ】【070-记票统计】
- 11招教你如何玩转数据库设计
- Failed to find provider info for com.tencent.mm.sdk.plugin.provider
- MAC OS PHP
- 【华为OJ】【069-简单错误记录】
- 上周热点回顾(5.9-5.15)
- 程序员为什么热衷造轮子