【组合&元素和问题】4Sum
来源:互联网 发布:php 执行exec 编辑:程序博客网 时间:2024/06/05 16:21
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)第一反应:DFS,但是超时了,擦擦
public class Solution { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); public void dfs(int [] num, ArrayList<Integer> l, int rs, int pos){ if(pos == num.length) return; if(l.size() == 4){ res.add(l); return ; } for(int i=pos; i<num.length; i++){ l.add(num[i]); dfs(num, new ArrayList(l), rs - num[i], i+1); l.remove(l.size()-1); } } public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { if(num == null) return null; Arrays.sort(num); ArrayList<Integer> l = new ArrayList<Integer>(); dfs(num, l, target, 0); return res; }}
解法二:将4个和转化成两个和问题(两个指针分两个方向指向数组)
三层for循环解决,O(n^3)
public class Solution { ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) { if(num == null) return null; Arrays.sort(num); int len = num.length; for(int i=0; i<len; i++){ if(i!=0 && num[i]==num[i-1]) continue; for(int j=i+1; j<len; j++){ if(j!=i+1 && num[j]==num[j-1]) continue; int p = j+1, q = len - 1; while(p < q){ if(p!=j+1 && num[p]==num[p-1]){ p++; continue; } if(q!=len-1 && num[q] == num[q+1]){ q--; continue; } int sum = num[i] + num[j] + num[p] + num[q]; if(sum == target){ ArrayList<Integer> l = new ArrayList<Integer>(); l.add(num[i]); l.add(num[j]); l.add(num[p]); l.add(num[q]); res.add(l); p++; } else if(sum < target) p++; else q--; } } } return res; }}
0 0
- 【组合&元素和问题】4Sum
- 【组合&元素和】3sum
- 【组合&元素和】3Sum Closest
- 数组元素组合问题分析
- Combination Sum 无序数组中找组合(每个元素可用多次)使得和为target@LeetCode
- Combination Sum II 无序数组中找组合(每个元素只能用一次)使得和为target@LeetCode@LeetCode
- LeetCode--------39. Combination Sum(组合和)
- python实现求解列表中元素的排列和组合问题
- 排列和组合问题
- 使用Linq求和方法Sum计算集合中多个元素和时应该注意的性能问题
- 动态规划问题系列---Minimum Path Sum(路线上元素和的最小值)
- 2sum问题和3sum问题
- 集合元素的排列和组合
- LeetCode | Combination Sum(元素的和)
- 什么是组合算法和组合问题
- noip2016组合数问题 组合+前缀和
- 全排列和组合问题
- Combination Sum II 组合数之和(包含有重复的元素)
- 实现NeatUpload大文件上传和个性显示进度条
- 请教关于c#界面数据传输问题
- 程序员面试、算法研究、编程艺术、红黑树、数据挖掘5大系列集锦
- java关键字之this
- exit
- 【组合&元素和问题】4Sum
- LabView 随机产生10000个不大于10000的非负整数,求没有出现的那些数
- BFS——Knight Moves
- 初学JZ2440之GPIO汇编点灯
- NYOJ-71 独木舟上的旅行
- java centos 6-64位 jdk1.7 安装及环境变量配置
- 合唱队形
- 教你如何迅速秒杀掉:99%的海量数据处理面试题
- iOS study Day14-浅复制