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

39 篇文章 1 订阅

给一个包含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, new ArrayList<Integer>(), target, res, 0);
        
        return res;
    }
    
    private void dfs(int[] numbers, List<Integer> list, int target, List<List<Integer>> res, int index){
        if(list.size() == 4){
            if(target == 0)
                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, list, target-numbers[i], res, i+1);
            list.remove(list.size()-1);
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值