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

23th Day| 39.组合总和,40.组合总和II,131.分割回文串

LeetCode 39 组合总和

题目链接:39.组合总和

//剪枝优化
class Solution {List<Integer> path = new ArrayList<>();List<List<Integer>> res = new ArrayList<>();public List<List<Integer>> combinationSum(int[] candidates, int target) {Arrays.sort(candidates);backtracking(candidates, target,0, 0);return res;}public void backtracking(int[] nums, int target, int sum, int startIndex){if(sum == target){res.add(new ArrayList(path));return;}for(int i = startIndex; i < nums.length; i++){if(sum+nums[i] > target) break;path.add(nums[i]);backtracking(nums, target,sum+nums[i], i);//取得是当前元素path.removeLast();}}
}

LeetCode 40 组合总和II

题目链接:40.组合总和II

class Solution {List<Integer> path = new ArrayList<>();List<List<Integer>> res = new ArrayList<>();public List<List<Integer>> combinationSum2(int[] candidates, int target) {Arrays.sort(candidates);backtracking(candidates, target, 0, 0);return res;}public void backtracking(int[] nums, int target, int sum, int startIndex){if(sum == target){res.add(new ArrayList(path));return;}for(int i = startIndex; i < nums.length; i++){if(sum+nums[i] > target) break;if(i != startIndex && nums[i-1] == nums[i]) continue;//i > startIndexpath.add(nums[i]);backtracking(nums, target, sum+nums[i], i+1);path.removeLast();}}
}

LeetCode 131 分割回文串

题目链接:131.分割回文串

class Solution {LinkedList<String> path = new LinkedList<>();List<List<String>> res = new ArrayList<>();public List<List<String>> partition(String s) {backtracking(s, 0 , new StringBuilder());return res;}//每一个for都需要一个新的StringBuilder;public void backtracking(String s, int startIndex, StringBuilder sb){if(startIndex == s.length()){res.add(new ArrayList(path));return;}for(int i = startIndex; i < s.length(); i++){sb.append(s.charAt(i));if(check(sb)){path.add(sb.toString());backtracking(s, i+1, new StringBuilder());path.removeLast();}else{continue;}}}public boolean check(StringBuilder sb){int i = 0;int j = sb.length() -1;while(i < j){if(sb.charAt(i++) != sb.charAt(j--)) return false;}return true;}
}

http://www.dtcms.com/a/312226.html

相关文章:

  • Linux—进程状态
  • 深入 Go 底层原理(九):context 包的设计哲学与实现
  • 智能手表:电源检查
  • Java多线程详解(2)
  • 一、灵巧手捉取几何原理——空间五指平衡捉取
  • GraphRag安装过程中的报错:系统找不到指定的文件(Could not install packages due to an OSError)
  • AI赋能测试:技术变革与应用展望
  • C++const成员
  • [网安工具] Web 漏洞扫描工具 —— AWVS · 使用手册
  • 机器学习【五】decision_making tree
  • Linux重定向和缓冲区
  • Piriority_queue
  • 三、摩擦刚体——捉取质量函数
  • ARP协议是什么?ARP欺骗是如何实现的?我们该如何预防ARP欺骗?
  • 前端与后端部署大冒险:Java、Go、C++三剑客
  • Codeforces Round 1039 (Div. 2) A-C
  • nodejs读写文件
  • 数据类型Symbol
  • 裸露土堆识别准确率↑32%:陌讯多特征融合算法实战解析
  • 数据结构基础
  • Minimizing Coins(Dynamic Programming)
  • 【智能体cooragent】创建 workflow 时 候选 Agent 和 Tool 获取来源详细分析
  • Python从入门到精通——第五章 列表与元组
  • 机器人学中路径规划(Path Planning)和轨迹生成(Trajectory Generation)关系
  • 海康皓视通 对接测试和比较
  • 【学习笔记】MySQL技术内幕InnoDB存储引擎——第8章 备份与恢复
  • 自进化智能体综述:通往人工超级智能之路
  • 安卓自动点击器:设置点击周期 / 滑动,抢票、游戏刷日常秒会
  • UNet改进(28):KD Attention增强UNet的知识蒸馏方法详解
  • 适 配 器 模 式