代码随想录算法训练营第二十七天 | 39. 组合总和、40.组合总和II、131.分割回文串

本文主要是介绍代码随想录算法训练营第二十七天 | 39. 组合总和、40.组合总和II、131.分割回文串,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

39. 组合总和

题目链接:https://leetcode.cn/problems/combination-sum/
文档讲解:https://programmercarl.com/0039.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8C.html
视频讲解:https://www.bilibili.com/video/BV1KT4y1M7HJ

思路

  • 这道题和之前做过的组合区别在于每个数都可以重复使用,在代码中体现为,递归时startIndex的值不用+1。
  • 剪枝优化:先将数组从小到大排序。在递归前判断,如果 sum+candidates[i] > target,就没必要再递归。

代码

未剪枝

class Solution {List<List<Integer>> res = new ArrayList<>();List<Integer> path = new ArrayList<>();public List<List<Integer>> combinationSum(int[] candidates, int target) {backtracking(candidates, target, 0, 0);return res;}public void backtracking(int[] candidates, int target, int sum, int startIndex) {if (sum == target) {res.add(new ArrayList<>(path));return;}    if (sum > target) return; for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {path.add(candidates[i]);backtracking(candidates, target, sum + candidates[i], i); // 不用i+1,因为当前节点可以重复被使用path.removeLast();}    }
}

剪枝优化

class Solution {List<List<Integer>> res = new ArrayList<>();List<Integer> path = 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[] candidates, int target, int sum, int startIndex) {if (sum == target) {res.add(new ArrayList<>(path));return;}    if (sum > target) return;for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) { // 剪枝path.add(candidates[i]);backtracking(candidates, target, sum + candidates[i], i); // 不用i+1,因为当前节点可以重复被使用path.removeLast();}    }
}

40.组合总和II

题目链接:https://leetcode.cn/problems/combination-sum-ii/
文档讲解:https://programmercarl.com/0040.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8CII.html
视频讲解:https://www.bilibili.com/video/BV12V4y1V73A

思路

  • 这道题和前面的组合总和的区别在于数组中有重复元素,而结果中要求没有重复数组。这就需要对树的每一层的数进行去重,同层的数不能相等。因为要判断相邻元素是否相等,所以要先排序。
  • 去重方法一(我的思路):不使用标记数组。递归后判断当前数和数组中下一个数是否相等,如果相等就i++,跳过下一个元素。因为可能有多个重复的数,所以这里的判断用while而不是if
for (int i = startIndex; i < candidates.length; i++) {path.add(candidates[i]);backtracking(candidates, target, sum + candidates[i], i + 1);while (i + 1 < candidates.length && candidates[i] == candidates[i + 1]) i++; // 去重path.removeLast()
}

也可以和前一个数比较大小:

for (int i = startIndex; i < candidates.length; i++) {if ( i > start && candidates[i] == candidates[i - 1] ) continue; // 去重path.add(candidates[i]);backtracking(candidates, target, sum + candidates[i], i + 1);path.removeLast();
}
  • 去重方法二(卡哥的思路):使用标记数组。当前数和前一个数相等,并且前一个数的used为false,就需要去重。used之所以是false,说明两个数是同层的。如果uesd为true,说明被使用过,那上一个数就应该是上一层的数,而不是同层的数。
if (i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]) { // 去重continue;
}

代码

去重方法一

class Solution {List<List<Integer>> res = new ArrayList<>();List<Integer> path = 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[] candidates, int target, int sum, int startIndex) {if (sum == target) {res.add(new ArrayList<>(path));return;}if (sum > target) return;for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) { // 剪枝path.add(candidates[i]);backtracking(candidates, target, sum + candidates[i], i + 1);while (i + 1 < candidates.length && candidates[i] == candidates[i + 1]) i++; // 去重path.removeLast();}}
}

去重方法二

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

131.分割回文串

题目链接:https://leetcode.cn/problems/palindrome-partitioning/
文档讲解:https://programmercarl.com/0131.%E5%88%86%E5%89%B2%E5%9B%9E%E6%96%87%E4%B8%B2.html
视频讲解:https://www.bilibili.com/video/BV1c54y1e7k6

思路

  • 切割问题可以抽象为组合问题,每次选取的是切割的点,然后得到中间的一段字符串。所以我们只需要移动确定切割的起点和终点,然后截取他们中间的字符串。
  • 切割问题中递归的终止条件:当startIndex==s.length(),说明已经按照某种方案遍历完字符串,那么就可以提交一组切割方案了。
  • 判断回文串的方法:双指针法,从两端向中间靠拢。

代码

class Solution {List<List<String>> res = new ArrayList<>();List<String> path = new ArrayList<>();public List<List<String>> partition(String s) {backtracking(s, 0);return res;}public void backtracking(String s, int startIndex) {// startIndex控制的是起始位置,如果起始位置已经大于s的大小,说明已经找到了一组分割方案了if (startIndex >= s.length()) {res.add(new ArrayList<>(path));return;}for (int i = startIndex; i < s.length(); i++) {if (isPalindrome(s.substring(startIndex, i + 1))) {path.add(s.substring(startIndex, i + 1));backtracking(s, i + 1);path.removeLast();}}}public boolean isPalindrome(String s) {int left = 0, right = s.length() - 1;while (left < right) {if (s.charAt(left) != s.charAt(right)) return false;left++;right--;}return true;}
}

这篇关于代码随想录算法训练营第二十七天 | 39. 组合总和、40.组合总和II、131.分割回文串的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1027929

相关文章

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

Redis实现高效内存管理的示例代码

《Redis实现高效内存管理的示例代码》Redis内存管理是其核心功能之一,为了高效地利用内存,Redis采用了多种技术和策略,如优化的数据结构、内存分配策略、内存回收、数据压缩等,下面就来详细的介绍... 目录1. 内存分配策略jemalloc 的使用2. 数据压缩和编码ziplist示例代码3. 优化的

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

Python从Word文档中提取图片并生成PPT的操作代码

《Python从Word文档中提取图片并生成PPT的操作代码》在日常办公场景中,我们经常需要从Word文档中提取图片,并将这些图片整理到PowerPoint幻灯片中,手动完成这一任务既耗时又容易出错,... 目录引言背景与需求解决方案概述代码解析代码核心逻辑说明总结引言在日常办公场景中,我们经常需要从 W

使用Spring Cache本地缓存示例代码

《使用SpringCache本地缓存示例代码》缓存是提高应用程序性能的重要手段,通过将频繁访问的数据存储在内存中,可以减少数据库访问次数,从而加速数据读取,:本文主要介绍使用SpringCac... 目录一、Spring Cache简介核心特点:二、基础配置1. 添加依赖2. 启用缓存3. 缓存配置方案方案

MySQL的配置文件详解及实例代码

《MySQL的配置文件详解及实例代码》MySQL的配置文件是服务器运行的重要组成部分,用于设置服务器操作的各种参数,下面:本文主要介绍MySQL配置文件的相关资料,文中通过代码介绍的非常详细,需要... 目录前言一、配置文件结构1.[mysqld]2.[client]3.[mysql]4.[mysqldum

Python多线程实现大文件快速下载的代码实现

《Python多线程实现大文件快速下载的代码实现》在互联网时代,文件下载是日常操作之一,尤其是大文件,然而,网络条件不稳定或带宽有限时,下载速度会变得很慢,本文将介绍如何使用Python实现多线程下载... 目录引言一、多线程下载原理二、python实现多线程下载代码说明:三、实战案例四、注意事项五、总结引

IDEA与MyEclipse代码量统计方式

《IDEA与MyEclipse代码量统计方式》文章介绍在项目中不安装第三方工具统计代码行数的方法,分别说明MyEclipse通过正则搜索(排除空行和注释)及IDEA使用Statistic插件或调整搜索... 目录项目场景MyEclipse代码量统计IDEA代码量统计总结项目场景在项目中,有时候我们需要统计