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)); }
  • 相关阅读:
    LFU
    poj 3581 -- 后缀数组
    leetcode 679
    poj 两条线段接雨水
    poj 1696极角排序
    判断平面上是否有一条直线与所有线段相交
    洛谷P3808 【模板】AC自动机(简单版)
    Most Distant Point from the Sea UVA
    P2742 [USACO5.1]圈奶牛Fencing the Cows /【模板】二维凸包
    P2249
  • 原文地址:https://www.cnblogs.com/skillking/p/9581071.html
Copyright © 2011-2022 走看看