leetcode——Combination Sum II

题目:

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 

 

思路:

这种组合题目,首先想到递归方法。每次找准一个,往下一层递归就好了。

在思路上没有任何难度。但是有一些注意事项:

1,首先如例子所述,组成8 的不一定是1,7,还有7,1。这两个1虽然不是同一个元素1,但是

题目也是不允许的。因此,我们想到了set,其中不能有重复元素,但是set对于list来说如何判重呢?

转而想到使用list.contain()方法去比较是否有两个元素一模一样的list。

但是,若list1={1,7},list2={7,1},则list.contain()中是对这两个区别对待的。因此,需要在顺序上做一定排列。

即,两个list的比较中,不光是元素一样,元素的位置也必须一样。

所以,在递归寻找之前,先把candidate数组排序(利用Arrays.sort),这时出来的list1和list2就都是{1,7}了。

这样才能实现真正的去重。


AC代码:

public class Combination_Sum_II {
    private LinkedList<Integer> list = new LinkedList<Integer>();
    private LinkedList<List<Integer>> rst = new LinkedList<List<Integer>>();

    private void combine(int[] num, int begin, int target, int sum) {
        if (begin >= num.length) {
            if (sum == target)
                rst.add(new LinkedList<Integer>(list));

        } else {
            for (int i = begin; i < num.length; i++) {
                if (sum + num[i] < target) {
                    list.add(num[i]);
                    combine(num, i + 1, target, sum + num[i]);
                    list.removeLast();
                } else if (sum + num[i] == target) {
                    list.add(num[i]);
                    if (!rst.contains(list))
                        rst.add((List<Integer>) list.clone());
                    list.removeLast();
                }
            }
        }
    }

    public List<List<Integer>> combinationSum2(int[] num, int target) {
        Arrays.sort(num);
        combine(num, 0, target, 0);
        return rst;
    }

    public static void main(String[] args) {
        Combination_Sum_II combination_sum_ii = new Combination_Sum_II();
        int[] num = {10,1,2,7,6,1,5};
        int target = 1;

        List<List<Integer>> list = combination_sum_ii.combinationSum2(num, target);
        for (List lis : list) {
            for (Object integer : lis) {
                System.out.print(" " + integer);
            }
            System.out.println();
        }
    }
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值