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

回溯 | Java | LeetCode 39, 40, 131 做题总结(未完)

Java

Arrays.sort(数组) //排序
不讲究顺序的解答,都可以考虑一下排序是否可行。

39. 组合总和

错误解答

在写的时候需要注意,sum -= candidates[i];很重要,也是回溯的一部分。
解答重复了。是因为回溯的for循环理解错了。

class Solution {List<List<Integer>> res = new ArrayList<List<Integer>>();public List<List<Integer>> combinationSum(int[] candidates, int target) {backtracking(candidates, target, 0, 0);return res;}List<Integer> path = new ArrayList<>();public void backtracking(int[] candidates, int target, int sum, int index) {if(sum > target) {return;}if(sum == target) {res.add(new ArrayList<>(path));return;}for(int i=0; i<candidates.length; i++) {sum += candidates[i];path.add(candidates[i]);backtracking(candidates,target,sum,i);sum -= candidates[i];path.remove(path.size()-1);}}
}

在这里插入图片描述

正确

  • 修改成下面这样就对了
    在这里插入图片描述

优化

不讲究顺序的解答,都可以考虑一下排序是否可行。
剪枝要先排序。

class Solution {List<List<Integer>> res = new ArrayList<List<Integer>>();public List<List<Integer>> combinationSum(int[] candidates, int target) {Arrays.sort(candidates);backtracking(candidates, target, 0, 0);return res;}List<Integer> path = new ArrayList<>();public void backtracking(int[] candidates, int target, int sum, int index) {if(sum == target) {res.add(new ArrayList<>(path));return;}for(int i=index; i<candidates.length; i++) {sum += candidates[i];if (sum > target) break;path.add(candidates[i]);backtracking(candidates,target,sum,i);sum -= candidates[i];path.remove(path.size()-1);}}
}

40.组合总和II

想得太简单了……

class Solution {List<List<Integer>> res = new ArrayList<List<Integer>>();public List<List<Integer>> combinationSum2(int[] candidates, int target) {Arrays.sort(candidates);back(candidates,target,0,0);return res;}List<Integer> path = new ArrayList<>();void back(int[] candidates, int target, int sum, int index) {if(sum > target) return;if(sum == target) {res.add(new ArrayList(path));}for(int i=index; i<candidates.length; i++) {path.add(candidates[i]);sum+=candidates[i];back(candidates,target,sum,index+1);sum-=candidates[i];path.remove(path.size()-1);   }}
}

131.分割回文串

http://www.lryc.cn/news/388858.html

相关文章:

  • Linux系统上部署Whisper。
  • 申请一张含100个域名的证书-免费SSL证书
  • 爬数据是什么意思?
  • Pytorch实战(二)
  • wordpress 付费主题modown分享,可实现资源付费
  • 【INTEL(ALTERA)】NIOS II调试器中的重新启动按钮不起作用
  • Hive On Spark语法
  • 利用 fail2ban 保护 SSH 服务器
  • 在TkinterGUI界面显示WIFI网络摄像头(ESP32s3)视频画面
  • Yolov8训练时遇到报错SyntaxError: ‘image_weights‘ is not a valid YOLO argument.等问题解决方案
  • javaweb(四)——过滤器与监听器
  • 冗余电源的应用,哪些工作站支持冗余电源
  • [信号与系统]IIR滤波器与FIR滤波器相位延迟定量的推导。
  • Python海量数据处理脚本大集合:pyWhat
  • postgresql搭建
  • Web 品质标准
  • 深入理解PyTorch:原理与使用指南
  • 【MySQL事务】深刻理解事务隔离以及MVCC
  • 关于Mac mini 10G网口的问题
  • 计算机网络-第4章 网络层
  • pytorch跑手写体实验
  • 利用Java的`java.util.concurrent`包优化多线程性能
  • 软件著作权申请:开发者的重要保障与助力
  • WLAN Hostapd配置参数详解 - CN
  • Excel 宏录制与VBA编程 ——VBA编程技巧篇一 (Union方法、Resize方法、Cells方法、UseSelect方法、With用法)
  • 基于路径长度的样条插补算法(自动驾驶和路径跟踪控制适用)
  • net Framework OAuth2.0
  • 速盾:服务器cdn加速超时如何解决?
  • 2024年6月总结及随笔之打卡网红点
  • 《Windows API每日一练》7.4 状态报告上使用计时器