码农知识堂 - 1000bd
  •   Python
  •   PHP
  •   JS/TS
  •   JAVA
  •   C/C++
  •   C#
  •   GO
  •   Kotlin
  •   Swift
  • LeetCode.40. 组合总和 II


    LeetCode.40. 组合总和 II

    难度:medium

     

     本题可以和  LeetCode.39. 组合总和 对比分析,主要区别有两个:

    • 39题每个元素是可以重复取用的,所以startIndex = i;而本题目不能重复取用,所以 startIndex = i + 1;
    • 本题的集合为有重复元素的集合,但题目要求不能有重复组合,所以我们需要used数组来去重

    要去重的是“同一树层上的使用过”,如果判断同一树层上元素(相同的元素)是否使用过了呢。

    如果candidates[i] == candidates[i - 1] 并且 used[i - 1] == false,就说明:前一个树枝,使用了candidates[i - 1],也就是说同一树层使用过candidates[i - 1]。

    此时for循环里就应该做continue的操作

    在图中将used的变化用橘黄色标注上,可以看出在candidates[i] == candidates[i - 1]相同的情况下:

    • used[i - 1] == true,说明同一树枝candidates[i - 1]使用过
    • used[i - 1] == false,说明同一树层candidates[i - 1]使用过

    Java:

    1. class Solution {
    2. List> ans = new ArrayList>();
    3. List path = new ArrayList();
    4. int sum = 0;
    5. public List> combinationSum2(int[] candidates, int target) {
    6. // 需要使用used数组,所以需要排序
    7. Arrays.sort(candidates);
    8. boolean[] used = new boolean[candidates.length];
    9. backTracking(candidates, target, used, 0);
    10. return ans;
    11. }
    12. public void backTracking(int[] candidates, int target, boolean[] used, int startIndex) {
    13. if (sum == target) {
    14. ans.add(new ArrayList<>(path));
    15. return;
    16. }
    17. for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
    18. if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
    19. continue;
    20. }
    21. sum += candidates[i];
    22. path.add(candidates[i]);
    23. used[i] = true;
    24. backTracking(candidates, target, used, i + 1);
    25. sum -= candidates[i];
    26. path.remove(path.size() - 1);
    27. used[i] = false;
    28. }
    29. }
    30. }

  • 相关阅读:
    功夫再高也怕菜刀,产品经理的那些事
    【.NET Core】深入理解IO之Path
    FlutterUnit 周边 | 收录排序算法可视化
    springboot+vue+Elementui共享单车管理系统
    手写方法实现字符串例如:“123“与整型例如:123相互转化(面试必会)
    网页翻译软件-网页翻译软件排行榜
    @ControllerAdvice
    PCA算法(python版本)
    某问答社区App x-zse-96签名分析
    wsl和windows下编译C++以及函数重载和函数模板的问题记录
  • 原文地址:https://blog.csdn.net/weixin_45867071/article/details/126347585
  • 最新文章
  • 攻防演习之三天拿下官网站群
    数据安全治理学习——前期安全规划和安全管理体系建设
    企业安全 | 企业内一次钓鱼演练准备过程
    内网渗透测试 | Kerberos协议及其部分攻击手法
    0day的产生 | 不懂代码的"代码审计"
    安装scrcpy-client模块av模块异常,环境问题解决方案
    leetcode hot100【LeetCode 279. 完全平方数】java实现
    OpenWrt下安装Mosquitto
    AnatoMask论文汇总
    【AI日记】24.11.01 LangChain、openai api和github copilot
  • 热门文章
  • 十款代码表白小特效 一个比一个浪漫 赶紧收藏起来吧!!!
    奉劝各位学弟学妹们,该打造你的技术影响力了!
    五年了,我在 CSDN 的两个一百万。
    Java俄罗斯方块,老程序员花了一个周末,连接中学年代!
    面试官都震惊,你这网络基础可以啊!
    你真的会用百度吗?我不信 — 那些不为人知的搜索引擎语法
    心情不好的时候,用 Python 画棵樱花树送给自己吧
    通宵一晚做出来的一款类似CS的第一人称射击游戏Demo!原来做游戏也不是很难,连憨憨学妹都学会了!
    13 万字 C 语言从入门到精通保姆级教程2021 年版
    10行代码集2000张美女图,Python爬虫120例,再上征途
Copyright © 2022 侵权请联系2656653265@qq.com    京ICP备2022015340号-1
正则表达式工具 cron表达式工具 密码生成工具

京公网安备 11010502049817号