当前位置: 首页 > news >正文

【leetcode hot 100 39】组合总和

错误解法一:每一次回溯都遍历提供的数组

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<Integer>();
        int sum = 0;
        backtrack(candidates, target, result, temp, sum);
        return result;
    }

    public void backtrack(int[] candidates, int target, List result, List temp, int sum){
        if(sum==target){
            result.add(temp);
        }
        
        for(int i=0; i<candidates.length; i++){
            temp.add(candidates[i]);
            backtrack(candidates, target, result, temp, sum-candidates[i]);
            temp.remove(temp.size()-1);
        }
    }
}

错误原因:

  • 没有回溯中止条件
  • 未考虑到数字相同但是位置不同的情况,我们把这种情况也算作一次结果

解法一:(回溯法)每一次回溯尝试把第idx个数加进去,考虑重复使用candidates[idx],或不使用candidates[idx](即:跳过)

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<Integer>();
        int idx = 0; // 从第0个数开始回溯
        backtrack(candidates, target, result, temp, idx);
        return result;
    }

    public void backtrack(int[] candidates, int target, List result, List temp, int idx){
        // temp拿到所有candidate
        if (idx == candidates.length) {
            return;
        }

        if(target==0){
            result.add(new ArrayList<Integer>(temp)); // 这里要new,不能直接add temp
            return;
        }
        // 选择当前数
        if(target-candidates[idx]>=0){
            temp.add(candidates[idx]);
            backtrack(candidates, target-candidates[idx], result, temp, idx);
            temp.remove(temp.size()-1);

        }
        // 不选择当前数,直接回溯
        backtrack(candidates, target, result, temp, idx+1);
    }
}

注意:

  • 这里要new,不能直接result.add(temp)result.add(new ArrayList<Integer>(temp))
  • 结束标值:
    • temp拿到所有candidate
    • 找到和为target的序列
http://www.dtcms.com/a/82394.html

相关文章:

  • 查看GPU型号、大小;CPU型号、个数、核数、内存
  • Vue3 基础语法指南:响应式系统与 Ref 应用
  • JavaIO流的使用和修饰器模式(直击心灵版)
  • 1201. 【高精度练习】蜜蜂路线
  • vpc网络的原理
  • 【Android】基础架构(详细介绍)
  • HAL库定时器配置
  • 每日一题力扣3248.矩阵中的蛇c++
  • 第三章:单调队列
  • Java中的JSONObject对象
  • DeepSeek-R1论文深度解析:纯强化学习如何引爆LLM推理革命?
  • LeetCode[454]四数相加Ⅱ
  • 近期学习资料,尚未整理
  • Wpf Avalonia-实现中英文切换工程
  • VAE,以及概率分布的各种知识点
  • 抓包工具:fiddler和wireshark对比
  • Python Django入门(创建其他网页)
  • PreparedStatement 和 Statement 从 功能、性能、安全性、适用场景 等维度详细对比分析
  • 架构师面试(十九):IM 架构
  • 某视频的解密下载
  • 地理信息科学(GIS)专业的就业出路与转型新方向,传统就业领域VS新兴技术赛道
  • docker模拟Dos_SYN Flood拒绝服务攻击 (Ubuntu20.04)
  • MyBatis 的一次缓存与二次缓存
  • 任务型多轮对话(二)| 意图识别
  • pta 乐子人游戏
  • 调用feapder作为子程序时setting.py文件不起作用
  • C++标准库新部件:解锁编程新姿势
  • win注册表提示没有权限进行修改的解决方式
  • (十)方法的定义 方法的作用域
  • 玩客云 armbian 安装mqtt服务端