【一次过】Lintcode 58. 四数之和

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/88885974

给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。

样例

例1:

输入:[2,7,11,15],3
输出:[]

例2:

输入:[1,0,-1,0,-2,2],0
输出:
[[-1, 0, 0, 1]
,[-2, -1, 1, 2]
,[-2, 0, 0, 2]]

注意事项

四元组(a, b, c, d)中,需要满足a <= b <= c <= d

答案中不可以包含重复的四元组。


解题思路:

Lintcode 57. 三数之和类似

public class Solution {
    /**
     * @param numbers: Give an array
     * @param target: An integer
     * @return: Find all unique quadruplets in the array which gives the sum of zero
     */
    public List<List<Integer>> fourSum(int[] numbers, int target) {
        // write your code here
        List<List<Integer>> res = new ArrayList<>();
        
        Arrays.sort(numbers);
        dfs(numbers, target, new ArrayList<Integer>(), res, 0);
        
        return res;
    }
    
    private void dfs(int[] numbers, int target, List<Integer> list, List<List<Integer>> res, int index){
        if(list.size() == 4){
            int tmp = 0;
            for(int i=0; i<list.size(); i++)
                tmp += list.get(i);
            
            if(tmp == target)
                res.add(new ArrayList<Integer>(list));
            
            return;
        }
        
        for(int i=index; i<numbers.length; i++){
            if(i != index && numbers[i] == numbers[i-1])
                continue;
                
            list.add(numbers[i]);
            dfs(numbers, target, list, res, i+1);
            list.remove(list.size() - 1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/88885974