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

数据结构刷题(二十一):131分割回文串、78子集

1.分割回文串

题目链接

思路:回溯算法的组合方法(分割问题类似组合问题)。

流程图:红色竖杠就是startIndex。 for循环是横向走,递归是纵向走。

回溯三部曲:

  • 递归函数参数:字符串s和startIndex,因为是在同一个集合中进行分割或组合,就需要startIndex

  • 递归函数终止条件:只要切割线切到了字符串最后面,就终止,然后add到result数组中(这里默认已经判断回文了)

  • 单层搜索的逻辑:在for (int i = startIndex; i < s.size(); i++)循环中,我们定义了起始位置startIndex,那么 [startIndex, i] 就是要截取的子串。

解法:

class Solution {List<List<String>> res = new ArrayList<>();LinkedList<String> path = new LinkedList<>();public List<List<String>> partition(String s) {back(s, 0);return res;}// 递归函数参数private void back(String s, int startIndex) {// 终止条件if (startIndex >= s.length()){res.add(new ArrayList<>(path));return;}for (int i = startIndex; i < s.length(); i++){// 如果是回文子串就path.addif (isPalindrome(s, startIndex, i)){path.add(s.substring(startIndex, i + 1));}elsecontinue;back(s, i + 1);path.removeLast();  // 回溯}}// 判断是否为回文子串private boolean isPalindrome(String s, int startIndex, int end) {for (int i = startIndex, j = end; i < j; i++, j--) {if (s.charAt(i) != s.charAt(j)) {return false;}}return true;}
}

2.子集

题目链接

思路:这个题是典型的组合问题。

  • 子集是收集树形结构中树的所有节点的结果

  • 而组合问题、分割问题是收集树形结构中叶子节点的结果

注意:for循环里,每次都要i<nums.length。

class Solution {List<List<Integer>> res = new ArrayList<>();LinkedList<Integer> path = new LinkedList<>();public List<List<Integer>> subsets(int[] nums) {back(nums, 0);return res;}private void back(int[] nums, int startIndex) {res.add(new ArrayList<>(path));for (int i = startIndex; i < nums.length; i++){path.add(nums[i]);back(nums, i + 1);path.removeLast();}}
}
http://www.lryc.cn/news/35962.html

相关文章:

  • Spring Aop 详解
  • 【数据库死锁】线上问题之数据库死锁
  • 好友管理系统--课后程序(Python程序开发案例教程-黑马程序员编著-第4章-课后作业)
  • Redis 集群 Redis Cluster搭建
  • 博客系统(前后端分离版)
  • 第十二章 opengl之模型加载(Assimp)
  • Stable Matching-稳定匹配问题【G-S算法,c++】
  • TypeScript(四)接口
  • Python-基础知识
  • 【java基础】集合基础说明
  • MySQL的下载及安装详细教程
  • SSL/TLS协议工作原理
  • 大数据项目实战之数据仓库:用户行为采集平台——第4章 用户行为数据采集模块
  • 《统计学习方法》(李航)——学习笔记
  • 阿里云EMR集群搭建及使用
  • 学习streamlit-4
  • 高级Oracle DBA面试题及答案
  • 程序员成长路线
  • 【Galois工具开发之路】关于类的重新装载思路
  • 哪款蓝牙耳机音质好?内行推荐四款高音质蓝牙耳机
  • Android程序自动在线升级安装
  • JS的BroadcastChannel与MessageChannel
  • nextjs开发 + vercel 部署 ssr ssg
  • Good Idea, 利用MySQL JSON特性优化千万级文库表
  • 【python游戏制作】快来跟愤怒的小鸟一起攻击肥猪们的堡垒吧
  • ARM 学习(一)
  • 深入分析Java的序列化与反序列化
  • 、Tomcat源码分析-类加载器
  • 反转链表相关的练习(下)
  • 2.进程和线程