18. 4Sum
Posted apanda009
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了18. 4Sum相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/4sum/#/solutions
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);
int max = num[num.length-1];
if (4 * num[0] > target || 4 * max < target)
return res;
for (int i=num.length-1; i>=3; i--) {
if (i<num.length-1 && num[i]==num[i+1]) continue;
threeSum(0, i-1, num, target-num[i], res, num[i]);
}
return res;
}
public void threeSum(int start, int end, int[] num, int target, List<List<Integer>> res, int last1) {
for (int i=end; i>=2; i--) {
if (i<end && num[i]==num[i+1]) continue;
twoSum(0, i-1, num, target-num[i], res, num[i], last1);
}
}
public void twoSum(int l, int r, int[] num, int target, List<List<Integer>> res, int last2, int last1) {
while (l < r) {
if (num[l]+num[r] == target) {
List<Integer> set = new ArrayList<Integer>();
set.add(num[l]);
set.add(num[r]);
set.add(last2);
set.add(last1);
res.add(new ArrayList<Integer>(set));
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) {
l++;
}
else {
r--;
}
}
}
}
以上是关于18. 4Sum的主要内容,如果未能解决你的问题,请参考以下文章