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

【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.kler.cn/a/595948.html

相关文章:

  • leetcode每日一题:最大或值
  • 发现一个好用的Vue.js内置组件
  • Bitcoin Thunderbolt 内测通道开启,加速比特币交易新时代
  • 大数据从入门到入魔系列————探索大数据前世今生之迷
  • 快速入手-基于Django的mysql操作(四)
  • stressapptest交叉编译(ARM64)
  • 批量删除 PPT 文档中的宏
  • D-Wave专用量子计算机登顶Science 率先展示在真实场景中的量子优势(内附下载)
  • 阿里云国际站代理商:如何延长服务器硬盘寿命?
  • 七天免登录 为什么不能用seesion,客户端的http请求自动携带cookei的机制(比较重要)涉及HTTP规范
  • 【数据结构】栈与队列:基础 + 竞赛高频算法实操(含代码实现)
  • 数组模拟邻接表 #图论
  • DeepBI:重构流量逻辑,助力亚马逊广告实现高效流量增长
  • 算法竞赛备赛——【数据结构】链表
  • 村民信息管理系统
  • WRF移动嵌套结合伏羲模型与CFD(PALM)高精度多尺度降尺度分析研究
  • 回顾一下-笔记
  • Ubuntu启动不了Terminal
  • 高级java每日一道面试题-2025年3月07日-微服务篇[Eureka篇]-Eureka Server和Eureka Client关系?
  • 挂谷问题与挂谷猜想:从平面转针到高维拓扑