代码随想录算法训练营第二十七天 | 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

相关文章

Java中的雪花算法Snowflake解析与实践技巧

《Java中的雪花算法Snowflake解析与实践技巧》本文解析了雪花算法的原理、Java实现及生产实践,涵盖ID结构、位运算技巧、时钟回拨处理、WorkerId分配等关键点,并探讨了百度UidGen... 目录一、雪花算法核心原理1.1 算法起源1.2 ID结构详解1.3 核心特性二、Java实现解析2.

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

Go语言代码格式化的技巧分享

《Go语言代码格式化的技巧分享》在Go语言的开发过程中,代码格式化是一个看似细微却至关重要的环节,良好的代码格式化不仅能提升代码的可读性,还能促进团队协作,减少因代码风格差异引发的问题,Go在代码格式... 目录一、Go 语言代码格式化的重要性二、Go 语言代码格式化工具:gofmt 与 go fmt(一)

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

Python如何去除图片干扰代码示例

《Python如何去除图片干扰代码示例》图片降噪是一个广泛应用于图像处理的技术,可以提高图像质量和相关应用的效果,:本文主要介绍Python如何去除图片干扰的相关资料,文中通过代码介绍的非常详细,... 目录一、噪声去除1. 高斯噪声(像素值正态分布扰动)2. 椒盐噪声(随机黑白像素点)3. 复杂噪声(如伪

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义