4Sum问题及解法
来源:互联网 发布:美萍汽车维修软件 编辑:程序博客网 时间:2024/04/30 07:25
问题描述:
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: 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]]
问题分析:
该问题与3Sum问题类似,大家可以先看看我对3Sum的解释。
3Sum问题及解法
详细过程见代码:
class Solution {public: vector<vector<int>> fourSum(vector<int>& nums, int target) { vector<vector<int> > res; if(nums.empty()) return res; sort(nums.begin(), nums.end()); for(int i = 0; i < nums.size(); i++) { int target_3 = target - nums[i]; for(int j = i + 1; j < nums.size(); j++) { int target_2 = target_3 - nums[j]; int front = j + 1; int back = nums.size() - 1; while(front < back) { int two_sum = nums[front] + nums[back]; if(two_sum < target_2) front++; else if(two_sum > target_2) back--; else { vector<int> quadruplet(4, 0); quadruplet[0] = nums[i]; quadruplet[1] = nums[j]; quadruplet[2] = nums[front]; quadruplet[3] = nums[back]; res.push_back(quadruplet); // 保证第三个元素不重复 while(front < back && nums[front] == quadruplet[2]) front++;} } // 保证第二个元素不会相同 while(j + 1 < nums.size() && nums[j + 1] == nums[j]) j++;}// 保证第一个元素不会相同while(i + 1 < nums.size() && nums[i + 1] == nums[i]) i++;}return res; }};
0 0
- 4Sum问题及解法
- 4Sum II问题及解法
- Two Sum问题及解法
- 3Sum问题及解法
- Path Sum问题及解法
- Combination Sum问题及解法
- Target Sum问题及解法
- 3Sum Closest问题及解法
- Sum of Two Integers问题及解法
- Sum of Left Leaves问题及解法
- Path Sum III问题及解法
- Combination Sum II问题及解法
- Minimum Path Sum问题及解法
- Path Sum II问题及解法
- Most Frequent Subtree Sum问题及解法
- Combination Sum III问题及解法
- Combination Sum IV问题及解法
- Map Sum Pairs问题及解法
- android适配需要知道的一些概念
- struts.xml 配置package标签里面的属性
- 9Club Online Casino Free Credit Beat Baccarat
- es批量搜索
- 基于RxJava的RxBus
- 4Sum问题及解法
- 算典04_例题_04_UVA-213
- 数据库事务
- spring多线程消费消息
- Java面试整理 错题集(上)
- C语言中一些常用IO函数的总结
- Faster RCNN代码理解(Python)
- Linux特殊权限命令
- 美国大选疑遭黑客入侵,网络安全威胁如何应对?