博客
关于我
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/

    你可能感兴趣的文章
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm scripts 使用指南
    查看>>
    npm should be run outside of the node repl, in your normal shell
    查看>>
    npm start运行了什么
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    npm 下载依赖慢的解决方案(亲测有效)
    查看>>
    npm 安装依赖过程中报错:Error: Can‘t find Python executable “python“, you can set the PYTHON env variable
    查看>>