Leetcode:给定一个数组,从其中选取三个数,要求三个数的和必须是0,求出所有这样的组合

package com.Test;

import java.util.ArrayList;
import java.util.Arrays;

/*给定一个数组,从其中选取三个数,要求三个数的和必须是0,求出所有这样的组合
 * dfs超时,但是方法扩展性强,可扩展到四个数、五个数的和是0;
 * 先固定一个,再利用双指针求解的方法不会超时
 */
public class ThreeSum {
	
	public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
		
		ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
		if(num == null || num.length <= 0)
			return res;
		
		Arrays.sort(num);
		dfs(num, new ArrayList<Integer>(), res, 0, 0, 3, 0);
		return res;
	}
	
	public void dfs(int[] num, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> res, 
			int start, int count, int len, int target) {
		//找到了符合条件的个数,且目标值为0
		if(count == len && target == 0 && !res.contains(list)) { 
			res.add(new ArrayList<Integer>(list));
			return;
		}
		//设置一个起点
		for(int i = start;i < num.length;i ++) {
			//已经搜索count + 1个数,还剩len - (count + 1)个数,剩下的最小和是num[i] * (len - (count + 1)),剩下的实际和是target - num[i]
			if(target - num[i] < num[i] * (len - count - 1)) {
				break;
			}
			list.add(num[i]);
			dfs(num, list, res, i + 1, count + 1, len, target - num[i]);
			list.remove(list.size()- 1);
		}
	}

    public ArrayList<ArrayList<Integer>> threeSum2(int[] num) {
		
		ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
		if(num == null || num.length <= 0)
			return res;
		
		Arrays.sort(num);
		for(int i = 0;i < num.length - 2;i ++) {
			//保证不要出现值相同的起点,避免重复搜索
			if(i == 0 || num[i] > num[i - 1]) {
				int j = i + 1;
				int k = num.length - 1;
				while(j < k) {
					if(num[i] + num[j] + num[k] == 0) {
						ArrayList<Integer> temp = new ArrayList<Integer>();
						temp.add(num[i]);
						temp.add(num[j]);
						temp.add(num[k]);
						if(!res.contains(temp)) 
							res.add(temp);
						j ++;
						k --;
						while(j < k && num[j] == num[j - 1]) {
							j ++;
						}
						
						while(j < k && num[k] == num[k + 1]) {
							k --;
						}
					}
					else if(num[i] + num[j] + num[k] < 0) {
						j ++;
					}
					else {
						k --;
					}
				}
			}
		}
		return res;
	}
	
	public static void main(String[] args) {
		
		int[] num = {-1,0,1,2,-1,-4};
		System.out.println(new ThreeSum().threeSum(num));
	}
}

猜你喜欢

转载自blog.csdn.net/zhou15755387780/article/details/81708551