博客
关于我
40. 组合总和 II(dfs、set去重)
阅读量:364 次
发布时间:2019-03-04

本文共 1477 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要找到所有可以组合起来的数字,使得它们的和等于目标数,并且每个数字只能在组合中使用一次。我们将使用深度优先搜索(DFS)来遍历所有可能的组合,同时确保生成的组合是唯一的。

方法思路

  • 排序数组:首先对数组进行排序,这有两个好处:一是可以帮助剪枝,二是有助于去重。
  • 深度优先搜索(DFS):使用递归的方式遍历所有可能的组合。每次递归,我们选择当前位置的数字,并将其加入当前路径。然后递归地继续选择下一个数字,直到满足目标和或穷尽所有可能性。
  • 剪枝:如果当前路径的和已经超过了目标数,就可以提前终止递归。
  • 去重:使用集合记录生成的路径字符串,以避免重复组合的生成。
  • 解决代码

    import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.util.List;import java.util.Set;import java.util.Stack;public class Solution {    List
    > res = new ArrayList<>(); Set
    set = new HashSet<>(); public List
    > combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); recursion(candidates, target, 0, 0, new Stack<>(), ""); return res; } private void recursion(int[] candidates, int target, int pos, int cur, Stack
    stack, String rec) { if (cur == target) { if (!set.contains(rec)) { set.add(rec); res.add(new ArrayList<>(stack)); } return; } if (pos == candidates.length) return; for (int i = pos; i < candidates.length; i++) { int num = candidates[i]; if (cur + num > target) break; stack.add(num); recursion(candidates, target, i + 1, cur + num, stack, rec + num); stack.pop(); } }}

    代码解释

  • 排序数组:使用Arrays.sort对候选数组进行排序。
  • 递归函数recursion函数用于深度优先搜索,参数包括当前位置pos、当前和cur、路径栈stack、当前路径字符串rec
  • 剪枝条件:如果当前和cur加上当前数字超过目标数,就break递归,避免无效路径。
  • 生成路径:当当前和等于目标数时,将路径字符串添加到集合中,避免重复。将路径转换为列表并添加到结果列表中。
  • 这种方法确保了所有可能的组合都被探索,并且通过排序和字符串去重,避免了重复组合的生成。

    转载地址:http://tjgr.baihongyu.com/

    你可能感兴趣的文章
    NOPI读取Excel
    查看>>
    NoSQL&MongoDB
    查看>>
    NoSQL介绍
    查看>>
    NoSQL数据库概述
    查看>>
    Notadd —— 基于 nest.js 的微服务开发框架
    查看>>
    Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
    查看>>
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>