当前位置: 首页 > 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拿到所有candidateif (idx == candidates.length) {return;}if(target==0){result.add(new ArrayList<Integer>(temp)); // 这里要new,不能直接add tempreturn;}// 选择当前数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的序列
  • target-candidates[idx]>=0时,要选择当前数

http://www.mrgr.cn/news/95560.html

相关文章:

  • 算法 | 优化算法比较
  • 【leetcode hot 100 131】分割回文串
  • 1.向量数据库milvus standalone单机版搭建
  • 六西格玛遇上Python:统计学的高效实践场
  • 深入理解Java虚拟机(学习笔记)
  • 小米AX6000上安装tailscale
  • 使用DeepSeek翻译英文科技论文,以MarkDown格式输出,使用Writage 3.3.1插件转换为Word文件
  • 信奥赛CSP-J复赛集训(模拟算法专题)(27):P5016 [NOIP 2018 普及组] 龙虎斗
  • GitLens with `Commit Graph`
  • redis安装
  • LeetCode 每日一题 2025/3/17-2025/3/23
  • How to install samba on Linux mint 22.1
  • 数据库练习2
  • JVM垃圾回收笔记02-垃圾回收器
  • 论文阅读笔记:Denoising Diffusion Probabilistic Models (2)
  • 【记录一下】LMDeploy学习笔记及遇到的问题
  • 【算法】常见dp、多状态dp、背包问题、子序列问题
  • 蓝桥杯 劲舞团
  • 给语言模型增加知识逻辑校验智能,识别网络信息增量的垃圾模式
  • 大数据环境搭建