zoukankan      html  css  js  c++  java
  • DFS_40. 组合总和 II

    给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

    candidates 中的每个数字在每个组合中只能使用一次。

    说明:

    所有数字(包括目标数)都是正整数。
    解集不能包含重复的组合。 
    示例 1:

    输入: candidates = [10,1,2,7,6,1,5], target = 8,
    所求解集为:
    [
    [1, 7],
    [1, 2, 5],
    [2, 6],
    [1, 1, 6]
    ]

    示例 2:

    输入: candidates = [2,5,2,1,2], target = 5,
    所求解集为:
    [
      [1,2,2],
      [5]
    ]

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/combination-sum-ii


    思路:

    上一题的升级版?给定的数组元素允许重复了,上一题没有重复,上一题可以重复利用,这题不能重复利用

    基本都一样,不多说了,盘他

    class Solution {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            //记录最终的返回值
            List<List<Integer>> res = new LinkedList<>();
            //记录当前的路径
            Deque<Integer> path = new ArrayDeque<Integer>();
            int len = candidates.length;
            Arrays.sort(candidates);
            boolean [] isVisited = new boolean[len];
            dfs(len,target,0,isVisited,res,path,candidates);
            return res;
        }
    
        private void dfs(int len, int target, int first, boolean[] isVisited, List<List<Integer>> res, Deque<Integer> path, int[] candidates) {
            if (target == 0){
                res.add(new ArrayList<>(path));
                return;
            }
            for (int i = first; i < len; i++) {
                if (i != 0 && candidates[i] == candidates[i - 1] && !isVisited[i - 1]) {
                    continue;  // 防止重复
                }
                if (target < candidates[i]){
                    continue;
                }
                if (isVisited[i]){
                    continue;
                }
                path.add(candidates[i]);
                isVisited[i] = true;
                dfs(len, target - candidates[i], i, isVisited, res, path, candidates);
                isVisited[i] = false;
                path.remove(candidates[i]);
            }
        }
    }

    好像确实难了一点

  • 相关阅读:
    51nod 1416 两点 dfs
    Codeforces Round #424 (Div. 2) A-C
    Codeforces Round #423 (Div. 2) A-C
    Codeforces Round #422 (Div. 2) A-C
    HDU 6077 Time To Get Up 模拟
    51nod 1381 硬币游戏 概率
    51nod 1100 斜率最大 计算几何
    hihocoder 1287 : 数论一·Miller-Rabin质数测试 大质数判定
    字典树
    数论
  • 原文地址:https://www.cnblogs.com/zzxisgod/p/13373231.html
Copyright © 2011-2022 走看看