当前位置: 首页 > 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的序列

相关文章:

  • 查看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 架构
  • 某视频的解密下载
  • 航海王亚洲巡展、工厂店直销……上海多区推出“五五购物节”活动
  • 国台办:民进党当局所谓“对等尊严”,就是企图改变两岸同属一中
  • 圆桌|如何应对特朗普政府的关税霸凌?一种联合国视角的思考
  • 烟花秀、新航线、购物节......上海邮轮文化旅游节今日开幕
  • 澎湃回声|山东莱州、潍坊对“三无”拖拉机产销市场展开调查排查
  • 牛市早报|国家发改委:将推出做好稳就业稳经济推动高质量发展若干举措