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

相关文章

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Java中Map.Entry()含义及方法使用代码

《Java中Map.Entry()含义及方法使用代码》:本文主要介绍Java中Map.Entry()含义及方法使用的相关资料,Map.Entry是Java中Map的静态内部接口,用于表示键值对,其... 目录前言 Map.Entry作用核心方法常见使用场景1. 遍历 Map 的所有键值对2. 直接修改 Ma

深入解析 Java Future 类及代码示例

《深入解析JavaFuture类及代码示例》JavaFuture是java.util.concurrent包中用于表示异步计算结果的核心接口,下面给大家介绍JavaFuture类及实例代码,感兴... 目录一、Future 类概述二、核心工作机制代码示例执行流程2. 状态机模型3. 核心方法解析行为总结:三

python获取cmd环境变量值的实现代码

《python获取cmd环境变量值的实现代码》:本文主要介绍在Python中获取命令行(cmd)环境变量的值,可以使用标准库中的os模块,需要的朋友可以参考下... 前言全局说明在执行py过程中,总要使用到系统环境变量一、说明1.1 环境:Windows 11 家庭版 24H2 26100.4061

pandas实现数据concat拼接的示例代码

《pandas实现数据concat拼接的示例代码》pandas.concat用于合并DataFrame或Series,本文主要介绍了pandas实现数据concat拼接的示例代码,具有一定的参考价值,... 目录语法示例:使用pandas.concat合并数据默认的concat:参数axis=0,join=

C#代码实现解析WTGPS和BD数据

《C#代码实现解析WTGPS和BD数据》在现代的导航与定位应用中,准确解析GPS和北斗(BD)等卫星定位数据至关重要,本文将使用C#语言实现解析WTGPS和BD数据,需要的可以了解下... 目录一、代码结构概览1. 核心解析方法2. 位置信息解析3. 经纬度转换方法4. 日期和时间戳解析5. 辅助方法二、L

Python使用Code2flow将代码转化为流程图的操作教程

《Python使用Code2flow将代码转化为流程图的操作教程》Code2flow是一款开源工具,能够将代码自动转换为流程图,该工具对于代码审查、调试和理解大型代码库非常有用,在这篇博客中,我们将深... 目录引言1nVflRA、为什么选择 Code2flow?2、安装 Code2flow3、基本功能演示

IIS 7.0 及更高版本中的 FTP 状态代码

《IIS7.0及更高版本中的FTP状态代码》本文介绍IIS7.0中的FTP状态代码,方便大家在使用iis中发现ftp的问题... 简介尝试使用 FTP 访问运行 Internet Information Services (IIS) 7.0 或更高版本的服务器上的内容时,IIS 将返回指示响应状态的数字代

MySQL 添加索引5种方式示例详解(实用sql代码)

《MySQL添加索引5种方式示例详解(实用sql代码)》在MySQL数据库中添加索引可以帮助提高查询性能,尤其是在数据量大的表中,下面给大家分享MySQL添加索引5种方式示例详解(实用sql代码),... 在mysql数据库中添加索引可以帮助提高查询性能,尤其是在数据量大的表中。索引可以在创建表时定义,也可

使用C#删除Excel表格中的重复行数据的代码详解

《使用C#删除Excel表格中的重复行数据的代码详解》重复行是指在Excel表格中完全相同的多行数据,删除这些重复行至关重要,因为它们不仅会干扰数据分析,还可能导致错误的决策和结论,所以本文给大家介绍... 目录简介使用工具C# 删除Excel工作表中的重复行语法工作原理实现代码C# 删除指定Excel单元