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]);
            }
        }
    }

    好像确实难了一点

  • 相关阅读:
    php中的一些需要注意点
    提权以及反弹shell一些方法
    SVN源码泄露漏洞
    网易白帽子视频的一些笔记
    sql注入的一些笔记
    URL中的"#"、"?"、"&"号的作用
    Asp.net mvc基础(十五)EF原理及SQL监控
    Asp.net mvc基础(十四)Entity Framework
    Asp.net mvc基础(十三)集合常用的扩展方法和Linq语句
    Linux运维基础(二)网络常见问题
  • 原文地址:https://www.cnblogs.com/zzxisgod/p/13373231.html
Copyright © 2011-2022 走看看