zoukankan      html  css  js  c++  java
  • 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)); }
  • 相关阅读:
    离散数学--第十章 群,环,域
    离散数学--十一章 格与布尔代数
    matplotlib 基础|笔记
    CF Round #632 div2
    Codeforces Round#630 div2
    PVZ 2--攻略合集?
    【POJ
    【POJ
    【Aizu
    【Aizu
  • 原文地址:https://www.cnblogs.com/skillking/p/9581071.html
Copyright © 2011-2022 走看看