4Sum

Given an array S of n integers, are there elements abc, 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代码:
  1. ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer>>();
  2. public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
  3. ArrayList<Integer> cur = new ArrayList<Integer>();
  4. Arrays.sort(num);
  5. int len = num.length;
  6. if(len<4) return res;
  7. for(int i=0;i<len-3;i++) {
  8. if(i>0 && num[i] == num[i-1]) continue;
  9. for(int j=i+1;j<len-2;j++) {
  10. if(j>i+1 && num[j] == num[j-1]) continue;
  11. int sum = target - num[i] - num[j];
  12. int start = j+1;
  13. int end = len-1;
  14. while(start < end) {
  15. if(num[start] + num[end] == sum) {
  16. cur.add(num[i]);
  17. cur.add(num[j]);
  18. cur.add(num[start]);
  19. cur.add(num[end]);
  20. res.add(new ArrayList<Integer>(cur));
  21. start++;
  22. while(start<end&&num[start]==num[start-1]) start++;
  23. end--;
  24. while(end>start&&num[end]==num[end+1]) end--;  //不要写成num[end] == num[end-1]
  25. cur.clear();
  26. } else if(num[start] + num[end] > sum) {
  27. end--;
  28. while(end>start&&num[end]==num[end+1]) end--;
  29. } else {
  30. start++;
  31. while(start<end&&num[start]==num[start-1]) start++;
  32. }
  33. }
  34. }
  35. }
  36. return res;
  37. }
posted @ 2014-07-11 23:37  purejade  阅读(74)  评论(0)    收藏  举报