40. Combination Sum II

一、题目

  1、审题

  2、分析:

    给出一个可以有重复数字的数组,一个目标数字 target,求数组中的所有和为 target 的数字组合,其中数组中每个元素只能用一次。

二、解答

  1、思路:

    利用DFS方法,其中,可以用   while(i + 1 < candidates.length && candidates[i] == candidates[i+1]) i++; 来过滤重复。

public List<List<Integer>> combinationSum2(int[] candidates, int target) {


        List<List<Integer>> targetList = new ArrayList<List<Integer>>();
        ArrayList<Integer> resultList = new ArrayList<Integer>();

        Arrays.sort(candidates);
        getResult2(targetList, resultList, candidates,  target, 0);
        return targetList;
    }

    private void getResult2(List<List<Integer>> targetList,
                            ArrayList<Integer> resultList, int[] candidates, int target, int start) {

        if(target > 0) {
            for (int i = start; i < candidates.length && candidates[i] <= target; i++) {

                
                resultList.add(candidates[i]);
                getResult2(targetList, resultList, candidates, target-candidates[i], i+1);
                resultList.remove(resultList.size() - 1);

          while(i + 1 < candidates.length && candidates[i] == candidates[i+1]) i++; } }
else if(target == 0) targetList.add(new ArrayList<Integer>(resultList)); }
原文地址:https://www.cnblogs.com/skillking/p/9581071.html