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)); }
  • 相关阅读:
    docker备忘录
    GUAVA-RateLimit
    JDK各版本发展史
    C++ 基础备忘录
    浅谈MES
    MES在流程和离散制造企业的15个差别!
    mysql连接oracle补偿方案—odbc驱动
    WinForm控件Chart的图表类型
    C#的异常处理机制(try...catch...finally)
    oracle 横向列变为纵向列
  • 原文地址:https://www.cnblogs.com/skillking/p/9581071.html
Copyright © 2011-2022 走看看