4Sum
来源:互联网 发布:彩虹六号 淘宝 编辑:程序博客网 时间:2024/06/04 17:47
题目:
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;}}
还有一种解法,闲了再研究(*^__^*) ……
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
- crunch使用说明
- Kali 2.0 安装 Cobalt Strike
- 进程和线程的区别
- 局部敏感哈希LSH(Locality Sensitive Hashing)
- LintCode | Easy | 链表倒数第n个节点 | Nth to Last Node in List
- 4Sum
- 浅谈MySQL中优化sql语句查询常用的30种方法
- Git Learner Record
- nyoj 60 谁获得了最高奖学金
- Swift快速入门-3-運算子、運算元
- shiro默认拦截器
- oracle子查询
- LSTM与GRU的一些比较--论文笔记
- 空类的sizeof为1