标签:
1 题目:
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:
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 思路
首先,得理解3Sum。
然后按照3Sum的思路,就好做了。主要是要遍历所有的四个组合。排序是肯定的。详情见代码吧,自己想的。。时间复杂度o(n^3)做了几题,感觉有点状态了。
3 代码
public List<List<Integer>> fourSum(int[] nums, int target) { List<List<Integer>> result = new ArrayList<List<Integer>>(); int len = nums.length; if(len < 4){ return result; } Arrays.sort(nums); int head = 0; int end = len-1; while(head < end -2){ while(head < end-2){ int pre = head + 1; int suffix = end - 1; /* compare all four group between pre & suffic */ while(pre < suffix){ int sum = nums[head]+nums[end]+nums[pre]+nums[suffix]; if(sum < target){ ++pre; }else if(sum > target){ --suffix; }else{ result.add(Arrays.asList(nums[head],nums[pre],nums[suffix],nums[end])); ++pre; --suffix; while(pre <= suffix && nums[pre]==nums[pre-1]) ++pre; while(pre <= suffix && nums[suffix]==nums[suffix+1]) --suffix; } } /* for each nums[head], compore all nums[head] until head<end-2 */ ++head; while(head<end-2 && nums[head]==nums[head-1]) ++head; } /* set head to 0 & end-1 ,so we can traverse all four groups */ head=0; --end; while(head<end-2 &&nums[end] == nums[end+1]) --end; } return result; }
标签:
原文地址:http://www.cnblogs.com/lingtingvfengsheng/p/4779531.html