4Sum
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)
思想:和3sum一致,将n^4转化为n^3
注意事项:end和后一项相等,则向前递归
java代码:
- ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer>>();
- public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
- ArrayList<Integer> cur = new ArrayList<Integer>();
- Arrays.sort(num);
- int len = num.length;
- if(len<4) return res;
- for(int i=0;i<len-3;i++) {
- if(i>0 && num[i] == num[i-1]) continue;
- for(int j=i+1;j<len-2;j++) {
- if(j>i+1 && num[j] == num[j-1]) continue;
- int sum = target - num[i] - num[j];
- int start = j+1;
- int end = len-1;
- while(start < end) {
- if(num[start] + num[end] == sum) {
- cur.add(num[i]);
- cur.add(num[j]);
- cur.add(num[start]);
- cur.add(num[end]);
- res.add(new ArrayList<Integer>(cur));
- start++;
- while(start<end&&num[start]==num[start-1]) start++;
- end--;
- while(end>start&&num[end]==num[end+1]) end--; //不要写成num[end] == num[end-1]
- cur.clear();
- } else if(num[start] + num[end] > sum) {
- end--;
- while(end>start&&num[end]==num[end+1]) end--;
- } else {
- start++;
- while(start<end&&num[start]==num[start-1]) start++;
- }
- }
- }
- }
- return res;
- }

浙公网安备 33010602011771号