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的扩展
public List<List<Integer>> fourSum(int[] num, int target) {
		List<List<Integer>> result = new ArrayList<List<Integer>>();
		if (num == null || num.length < 4) {
			return result;
		}
		int temp = Integer.MAX_VALUE;
		Arrays.sort(num);
		for (int i = 0; i < num.length - 3; i++) {
			int tar3 = target - num[i];
			while (temp == tar3 && i < num.length - 3) {
				i++;
				tar3 = target - num[i];
			}
			List<List<Integer>> res3 = threeSum(num, tar3, i + 1,
					num.length - 1);
			for (List<Integer> ls : res3) {
				ls.add(0, num[i]);
				result.add(ls);
			}
			temp = tar3;
		}
		return result;
	}

	public List<List<Integer>> threeSum(int[] num, int target, int begin,
			int end) {
		List<List<Integer>> result = new ArrayList<List<Integer>>();
		int temp = Integer.MAX_VALUE;
		for (int i = begin; i < end; i++) {
			int tar = target - num[i];
			while (temp == tar && i < end) {
				i++;
				tar = target - num[i];
			}
			int less = i + 1;
			int over = end;
			while (less < over) {
				if (tar > num[less] + num[over]) {
					less++;
					while (num[less] == num[less - 1] && less < over) {
						less++;
					}
				} else if (tar < num[less] + num[over]) {
					over--;
					while (num[over] == num[over + 1] && over > less) {
						over--;
					}

				} else {
					int[] c = { num[i], num[less], num[over] };
					List<Integer> temp1 = new ArrayList<Integer>();
					for (int k : c) {
						temp1.add(k);
					}
					result.add(temp1);
					over--;
					while (num[over] == num[over + 1] && over > less) {
						over--;
					}
					less++;
					while (num[less] == num[less - 1] && less < over) {
						less++;
					}
				}
			}
			temp = tar;
		}

		return result;
	}

你可能感兴趣的:(SUM)