LeetCode40 Combination Sum II

来源:互联网 发布:淘宝vr眼镜效果怎么样 编辑:程序博客网 时间:2024/05/21 19:49

原题:


英:
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.
The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8。

中:
给定一个候选数字(C)和目标数(T)的集合,在C中找出所有的组合,在C中,候选数字和T。
C中的每个数字只能在组合中使用一次。
注意:
所有的数字(包括目标)都是正整数。
解决方案集不能包含重复的组合。
例如,给定的候选集[10、1、2、7、6、1、5]和目标8。


解题思路:

本题与第39题类似,同样用到递归,但是有些不同,每个数只能抽取一次且数组中的数可以重复。在这里,对39题的代码稍加改动即可。代码如下:

public class Solution {    public List<List<Integer>> combinationSum2(int[] candidates, int target) {        List<List<Integer>> res = new ArrayList();        List<Integer> ans = new ArrayList<Integer>();        Arrays.sort(candidates);//先把数组排序了,这样list中重复的是一样的。        combinationIteration(res,ans,candidates,target,0);        List<List<Integer>> finalRes = new ArrayList(new HashSet(res));//利用set的性质去掉list中重复的值        return finalRes;    }    private void combinationIteration(List<List<Integer>> res,            List<Integer> ans, int[] candidates, int target,int start) {        if(target==0){            List<Integer> tmp = new ArrayList<Integer>(ans);            res.add(tmp);        }if(target<0){            return;        }        for(int i=start; i<candidates.length;i++){            ans.add(candidates[i]);            combinationIteration(res, ans, candidates, target-candidates[i], i+1);//这里i+1是与39题的区别,意味着不能重复选取            ans.remove(ans.size()-1);        }    } }

重点说明:

由于只能取一次并且list不能重复,所以首先将数组排序,使抽取变得有顺序,然后在最后再利用set的性质去掉list中重复的值。同时,在递归的时候也有所不同,注释中有解释。