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)); }
  • 相关阅读:
    java 笔记(6) static关键字
    java 笔记(5)接口,static
    java 笔记(4)抽象类与抽象方法
    java 笔记(3)多态 容易理解
    看穿CSS的定位技术
    揭开浮动布局的秘密(简略版)
    不可不知的CSS盒子模型(简略版)
    初学Java web 项目
    Eclipse快捷键
    JDBC连接数据库
  • 原文地址:https://www.cnblogs.com/skillking/p/9581071.html
Copyright © 2011-2022 走看看