4Sum
2015-10-01 14:20
253 查看
题目:
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.
分析:
2-sum,3-sum,4-sum
http://blog.csdn.net/linhuanmars/article/details/24826871
还有一种解法,闲了再研究(*^__^*) ……
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)
分析:
2-sum,3-sum,4-sum
http://blog.csdn.net/linhuanmars/article/details/24826871
public class Solution { public List<List<Integer>> fourSum(int[] num, int target) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if(num==null||num.length==0) return res; Arrays.sort(num); for(int i=num.length-1;i>2;i--) { if(i==num.length-1 || num[i]!=num[i+1]) { ArrayList<ArrayList<Integer>> curRes = threeSum(num,i-1,target-num[i]); for(int j=0;j<curRes.size();j++) { curRes.get(j).add(num[i]); } res.addAll(curRes); } } return res; } private ArrayList<ArrayList<Integer>> threeSum(int[] num, int end, int target) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); for(int i=end;i>1;i--) { if(i==end || num[i]!=num[i+1]) { ArrayList<ArrayList<Integer>> curRes = twoSum(num,i-1,target-num[i]); for(int j=0;j<curRes.size();j++) { curRes.get(j).add(num[i]); } res.addAll(curRes); } } return res; } private ArrayList<ArrayList<Integer>> twoSum(int[] num, int end, int target) { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); int l=0; int r=end; while(l<r) { if(num[l]+num[r]==target) { ArrayList<Integer> item = new ArrayList<Integer>(); item.add(num[l]); item.add(num[r]); res.add(item); l++; r--; while(l<r&&num[l]==num[l-1]) l++; while(l<r&&num[r]==num[r+1]) r--; } else if(num[l]+num[r]>target) { r--; } else { l++; } } return res; } }
还有一种解法,闲了再研究(*^__^*) ……
相关文章推荐
- 算法题查询学生成绩
- JavaScript高级程序设计之函数表达式之私有变量之模块模式第7.4.2讲笔记
- Android版本更新之本地数据库更新
- NetWorkTool工具类之网络请求
- mac下cocoaPods的安装和使用
- 安卓调用unity的3D界面
- 获取HTML标签当前在网页中的绝对位置
- cuda 异步函数
- maven的settings.xml详细说明
- js获取网页选中部分的内容,包含html代码
- bzoj 3333: 排队计划 解决问题的方法
- javascript如何获取当前网页的源码
- 【转】--在Android源码树中添加userspace I2C读写工具(i2c-util)
- 构建高性能WEB之HTTP首部优化
- jg-table 过程2 ( jgTable )
- ramoops具体失败原因来解释驱动寄存器
- 程序猿抱大招
- dictionary
- [CareerCup] 9.11 Parenthesize the Expression 表达式加括号
- zw版·全程图解Halcon控件安装(delphi2007版)