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

每日算法Day15【组合、组合总和III、电话号码的字母组合】

77. 组合

算法链接:

77. 组合 - 力扣(LeetCode)
类型: 回溯
难度: 中等

回溯三步法:
1、确定参数返回值

2、确定终止条件

3、单层搜索逻辑

剪枝操作:
当path容量超过k时的数据可以不用遍历,故遍历边界条件判断:

for(int i = startIndex;i<= n - (k - path.size()) + 1 ; i++)

题解:

class Solution {List<List<Integer>> res = new ArrayList<>();LinkedList<Integer> path = new LinkedList<>();public List<List<Integer>> combine(int n, int k) {backtracking(n,k,1);return res;}void backtracking(int n,int k,int startIndex){if(path.size()==k){res.add(new ArrayList<>(path));return;}for(int i = startIndex;i<= n - (k - path.size()) + 1 ; i++){path.add(i);backtracking(n,k,i+1);path.removeLast();}}
}

216.组合总和III

算法链接:

216. 组合总和 III - 力扣(LeetCode)
类型: 回溯
难度: 中等

剪枝思路:

当路径总和大于n或者路径数大于k时,return

题解:

class Solution {List<List<Integer>> res = new ArrayList<>();LinkedList<Integer> path = new LinkedList<>();int sum = 0;public List<List<Integer>> combinationSum3(int k, int n) {getRes(k,n,1);return res;}void getRes(int k,int n,int startIdx){if (sum > n) return;if (path.size() > k) return;if (path.size()==k && sum == n){res.add(new ArrayList<>(path));return;}for(int i = startIdx;i<= 9 ; i++){path.add(i);sum+=i;getRes(k,n,i+1);sum-=i;path.removeLast();}}
}

17.电话号码的字母组合

算法链接:

17. 电话号码的字母组合 - 力扣(LeetCode)
类型: 回溯
难度: 中等

思路:将题意构建二叉树数据结构,并且使用数组存储号码值

题解:

class Solution {List<String> res = new ArrayList<>();String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};StringBuilder path = new StringBuilder();public List<String> letterCombinations(String digits) {if(digits == null || digits.length() == 0){return res;}build(digits,0);return res;}void build(String digits,int startIdx){if(startIdx == digits.length()){res.add(path.toString());return;}String str = numString[digits.charAt(startIdx)-'0'];for(int i = 0;i<str.length();i++){path.append(str.charAt(i));build(digits,startIdx+1);path.deleteCharAt(path.length()-1);}}
}
http://www.lryc.cn/news/519050.html

相关文章:

  • C语言教程——指针进阶(2)
  • 调和级数不为整数的证明
  • 基于微信小程序的在线学习系统springboot+论文源码调试讲解
  • 基于 Boost.Asio 和 Boost.Beast 的异步 HTTP 服务器(学习记录)
  • 有机物谱图信息的速查技巧有哪些?
  • Eureka缓存机制
  • 【LC】78. 子集
  • 协同过滤算法私人诊所系统|Java|SpringBoot|VUE|
  • Docker部署Naocs-- 超细教程
  • [java基础-集合篇]优先队列PriorityQueue结构与源码解析
  • 12. C语言 数组与指针(深入理解)
  • Postman接口测试基本操作
  • MySQL--2.1MySQL的六种日志文件
  • spring task使用
  • 【FPGA】时序约束与分析
  • LLM的MoE由什么构成:门控网络,专家网络
  • HTML-多媒体标签
  • MySQL笔记大总结20250108
  • stm32week3
  • uniapp 的uni.getRecorderManager() 录音功能小记
  • 【面试题】技术场景 4、负责项目时遇到的棘手问题及解决方法
  • RT-DETR代码详解(官方pytorch版)——参数配置(1)
  • 腾讯云AI代码助手编程挑战赛-凯撒密码解码编码器
  • 搭建docker私有化仓库Harbor
  • 【Vim Masterclass 笔记09】S06L22:Vim 核心操作训练之 —— 文本的搜索、查找与替换操作(第一部分)
  • GIC中断分组介绍(IMX6ull为例)
  • 计算机网络期末复习(知识点)
  • Apache XMLBeans 一个强大的 XML 数据处理框架
  • 飞凌嵌入式i.MX8M Mini核心板已支持Linux6.1
  • 【数据链电台】洛克希德·马丁(Lockheed Martin)