Combination Sum II

本文解析了一道比Combination Sum更简单的算法题——组合总和II,详细介绍了如何通过递归实现不重复使用元素的组合查找,并给出了完整的Java代码实现。

这道题比Combination Sum还要简单,因为每个数不能重复使用,所以只需要从下一个开始即可,和subset II一样

public class Solution {
    /**
     * @param num: Given the candidate numbers
     * @param target: Given the target number
     * @return: All the combinations that sum to target
     */
    public List<List<Integer>> combinationSum2(int[] num, int target) {
        // write your code here
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        if(num.length == 0 || num == null){
            return result;
        }
        List<Integer> list = new ArrayList<Integer>();
        Arrays.sort(num);
        helper(result, list, num, target, 0);
        return result;
    }
    
    private void helper(List<List<Integer>> result, List<Integer> list, 
                        int[] num, int target, int pos){
        if (target == 0){
            result.add(new ArrayList<Integer>(list));
        }
        
        for(int i = pos; i < num.length; i++){
            if (num[i] > target){
                break;
            }
            
            if (i > pos && num[i] == num[i-1]){
                continue;
            }
            list.add(num[i]);
            helper(result, list, num, target - num[i], i+1);
            list.remove(list.size() - 1);
        }
                            
    }
}

 

转载于:https://www.cnblogs.com/codingEskimo/p/5782626.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值