backTrack Mock

1.简而言之,一个集合里求组合就要用startIndex。

2.startIndex本身保证了组合的不同,需要求不同组合就要用startIndex;但从 i 开始还是从 i + 1 开始决定了组合元素能不能重复选。(39)

3.组内既不能重复选,也不能有重复组合,数组中还有重复元素,就要sort(40)

4.startIndex就是取了后面的不能取前面的所以保证不同的组合,但是排列不存在这个问题所以不用startIndex

5.切割就是组合

6.子集是收集路径的组合

112,113,257

combination 77,39,40,216,17

partitioning 131,93

subsets 78,90

permutations 46,47

51,37

491,332

112. Path Sum

Easy

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

leaf is a node with no children.

class Solution {public boolean hasPathSum(TreeNode root, int targetSum) {if(root == null){return false;}if(root.left == null && root.right == null){return root.val == targetSum;}boolean left = false;boolean right = false;if(root.left != null){left = hasPathSum(root.left , targetSum - root.val);}if(root.right != null){right = hasPathSum(root.right , targetSum - root.val);}return left || right;}
}

113. Path Sum II

Medium

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

class Solution {List<List<Integer>> ans = new ArrayList<>();List<Integer> path = new ArrayList<>();public List<List<Integer>> pathSum(TreeNode root, int targetSum) {dfs(root, targetSum);return ans;}private void dfs(TreeNode root , int targetSum){if(root == null){return;}path.add(root.val);if(root.left == null && root.right == null){if(root.val == targetSum){ans.add(new ArrayList(path));}}dfs(root.left , targetSum - root.val);dfs(root.right , targetSum - root.val);path.remove(path.size()-1);}
}
class Solution {List<List<Integer>> ans = new ArrayList<>();List<Integer> path = new ArrayList<>();public List<List<Integer>> pathSum(TreeNode root, int targetSum) {dfs(root, targetSum);return ans;}private void dfs(TreeNode root , int targetSum){if(root == null){return;}path.add(root.val);if(root.left == null && root.right == null){if(root.val == targetSum){ans.add(new ArrayList(path));}}if(root.left != null){dfs(root.left , targetSum - root.val);path.remove(path.size()-1);}if(root.right != null){dfs(root.right , targetSum - root.val);path.remove(path.size()-1);}}
}

257. Binary Tree Paths

Easy

Given the root of a binary tree, return all root-to-leaf paths in any order.

leaf is a node with no children.

class Solution {public List<String> binaryTreePaths(TreeNode root) {List<String> res = new ArrayList<>();// 存最终的结果if (root == null) {return res;}List<Integer> paths = new ArrayList<>();// 作为结果中的路径traversal(root, paths, res);return res;}private void traversal(TreeNode root, List<Integer> paths, List<String> res) {paths.add(root.val);// 前序遍历,中// 遇到叶子结点if (root.left == null && root.right == null) {// 输出StringBuilder sb = new StringBuilder();// StringBuilder用来拼接字符串,速度更快for (int i = 0; i < paths.size() - 1; i++) {sb.append(paths.get(i)).append("->");}sb.append(paths.get(paths.size() - 1));// 记录最后一个节点res.add(sb.toString());// 收集一个路径return;}// 递归和回溯是同时进行,所以要放在同一个花括号里if (root.left != null) { // 左traversal(root.left, paths, res);paths.remove(paths.size() - 1);// 回溯}if (root.right != null) { // 右traversal(root.right, paths, res);paths.remove(paths.size() - 1);// 回溯}}}
class Solution {List<String> ans = new ArrayList<>();List<Integer> path = new ArrayList<>();public List<String> binaryTreePaths(TreeNode root) {dfs(root);return ans;}private void dfs(TreeNode root){if(root == null){return;}path.add(root.val);if(root.left == null && root.right ==null){StringBuilder sb = new StringBuilder();// StringBuilder用来拼接字符串,速度更快for (int i = 0; i < path.size() - 1; i++) {sb.append(path.get(i)).append("->");}sb.append(path.get(path.size() - 1));// 记录最后一个节点ans.add(sb.toString());// 收集一个路径}dfs(root.left);dfs(root.right);path.remove(path.size()-1);}
}

77. Combinations

Medium

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].

You may return the answer in any order.

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

39. Combination Sum

Medium

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the 

frequency

 of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

class Solution {List<List<Integer>> ans = new ArrayList<>();List<Integer> path = new ArrayList<>();public List<List<Integer>> combinationSum(int[] candidates, int target) {backTrack(candidates, target, 0);return ans;}private void backTrack(int[] candidates, int target, int startIndex){if(target < 0 ){return;}if(target == 0){ans.add(new ArrayList(path));}for(int i = startIndex; i < candidates.length; i++){path.add(candidates[i]);backTrack(candidates, target-candidates[i], i);path.remove(path.size()-1);}}
}

40. Combination Sum II

Medium

Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

class Solution {List<List<Integer>> ans = new ArrayList<>();List<Integer> path = new ArrayList<>();public List<List<Integer>> combinationSum2(int[] candidates, int target) {Arrays.sort(candidates);backTrack(candidates,target,0);return ans;}private void backTrack(int[] candidates, int target, int startIndex){if(target == 0){ans.add(new ArrayList(path));return;}for(int i = startIndex; i < candidates.length; i++){if(target < 0){break;}if(i > startIndex && candidates[i] == candidates[i-1]){continue;}path.add(candidates[i]);backTrack(candidates, target - candidates[i], i + 1);path.remove(path.size()-1);}}
}

216. Combination Sum III

Medium

Find all valid combinations of k numbers that sum up to n such that the following conditions are true:

  • Only numbers 1 through 9 are used.
  • Each number is used at most once.

Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.

class Solution {List<List<Integer>> ans = new ArrayList<>();List<Integer> path = new ArrayList<>();public List<List<Integer>> combinationSum3(int k, int n) {backTrack(k, n, 1, 0);return ans;}private void backTrack(int k, int n, int startIndex, int sum){if(path.size() == k){if(sum == n){ans.add(new ArrayList(path));}return;}for(int i = startIndex; i <= 9; i++){path.add(i);backTrack(k, n, i + 1, sum + i);path.remove(path.size()-1);}}
}

17. Letter Combinations of a Phone Number

Medium

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

class Solution {List<String> ans = new ArrayList<>();public List<String> letterCombinations(String digits) {if (digits == null || digits.length() == 0) {return ans;}Map<Character, String> phoneMap = new HashMap<Character, String>() {{put('2', "abc");put('3', "def");put('4', "ghi");put('5', "jkl");put('6', "mno");put('7', "pqrs");put('8', "tuv");put('9', "wxyz");}};backTrack(digits, phoneMap, 0);return ans;}StringBuilder path = new StringBuilder();private void backTrack(String digits, Map<Character, String> phoneMap, int num) {if (num == digits.length()) {ans.add(path.toString());return;}char ch = digits.charAt(num);String str = phoneMap.get(ch);for (int i = 0; i < str.length(); i++) {path.append(str.charAt(i));backTrack(digits, phoneMap, num + 1);path.deleteCharAt(path.length() - 1);}}
}

131. Palindrome Partitioning

Medium

Given a string s, partition s such that every substring of the partition is a palindrome

. Return all possible palindrome partitioning of s.

Example 1:

Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
class Solution {List<List<String>> ans = new ArrayList<>();List<String> path = new ArrayList<>();public List<List<String>> partition(String s) {backTrack(s, 0);return ans;}private void backTrack(String s , int startIndex){if(startIndex == s.length()){ans.add(new ArrayList(path));return;}for(int i = startIndex; i < s.length(); i++){String str = s.substring(startIndex, i + 1);if(isPalindrome(s, startIndex,i)){path.add(str);}else{continue;}backTrack(s, i + 1);path.remove(path.size() - 1);}}private boolean isPalindrome(String s, int startIndex, int endIndex){int i = startIndex;int j = endIndex;while(i <= j){if(s.charAt(i) != s.charAt(j)){return false;}i++;j--;}return true;}
}

93. Restore IP Addresses

Medium

valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.

  • For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but "0.011.255.245""192.168.1.312" and "192.168@1.1" are invalid IP addresses.

Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.

Example 1:

Input: s = "25525511135"
Output: ["255.255.11.135","255.255.111.35"]
class Solution {List<String> ans = new ArrayList<>();StringBuilder path = new StringBuilder();public List<String> restoreIpAddresses(String s) {backTrack(s, 0, 0);return ans;}private void backTrack(String s, int startIndex, int count){if(count == 4 && startIndex == s.length()){//不仅等于4还要用完所有数字ans.add(path.deleteCharAt(path.length()-1).toString());return;}if(count > 4){return;}for(int i = startIndex; i < s.length() && i < startIndex + 3; i++){String str = s.substring(startIndex, i + 1);if(isTrue(str)){int len = path.length();path.append(str).append(".");backTrack(s, i + 1, count + 1);path.setLength(len);}}}private boolean isTrue(String s){if(s.length()>1 && s.charAt(0) == '0'){return false;}int a = Integer.parseInt(s);return a >=0 && a <= 255;}
}

78. Subsets

Medium

Given an integer array nums of unique elements, return all possible 

subsets

 (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

class Solution {List<List<Integer>> ans = new ArrayList<>();List<Integer> path = new ArrayList<>();public List<List<Integer>> subsets(int[] nums) {backTrack(nums, 0);return ans;}private void backTrack(int[] nums, int startIndex) {ans.add(new ArrayList<>(path));if (startIndex == nums.length) {return;}for (int i = startIndex; i < nums.length; i++) {path.add(nums[i]);backTrack(nums, i + 1);path.remove(path.size() - 1);}}
}

90. Subsets II

Medium

Given an integer array nums that may contain duplicates, return all possible 

subsets

 (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

class Solution {List<List<Integer>> ans = new ArrayList<>();List<Integer> path = new ArrayList<>();public List<List<Integer>> subsetsWithDup(int[] nums) {Arrays.sort(nums);backTrack(nums,0);return ans;}private void backTrack(int[] nums, int startIndex) {ans.add(new ArrayList<>(path));if (startIndex == nums.length) {return;}for (int i = startIndex; i < nums.length; i++) {if (i > startIndex && nums[i] == nums[i - 1]) {continue;}path.add(nums[i]);backTrack(nums, i + 1);path.remove(path.size() - 1);}}
}

46. Permutations

Medium

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

class Solution {List<List<Integer>> ans = new ArrayList<>();List<Integer> path = new ArrayList<>();boolean[] used;public List<List<Integer>> permute(int[] nums) {used = new boolean[nums.length];backTrack(nums);return ans;}private void backTrack(int[] nums) {if (path.size() == nums.length) {ans.add(new ArrayList<>(path));return;}for (int i = 0; i < nums.length; i++) {if (used[i] == false) {path.add(nums[i]);used[i] = true;backTrack(nums);path.remove(path.size() - 1);used[i] = false;}}}
}

47. Permutations II

Medium

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

class Solution {List<List<Integer>> ans = new ArrayList<>();List<Integer> path = new ArrayList<>();boolean[] used;public List<List<Integer>> permuteUnique(int[] nums) {used = new boolean[nums.length];Arrays.sort(nums);backTrack(nums);return ans;}private void backTrack(int[] nums) {if (path.size() == nums.length) {ans.add(new ArrayList<>(path));return;}for (int i = 0; i < nums.length; i++) {if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {//注意条件continue;}if (used[i] == false) {path.add(nums[i]);used[i] = true;backTrack(nums);used[i] = false;path.remove(path.size() - 1);}}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/814635.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【Java探索之旅】方法重载 递归

&#x1f3a5; 屿小夏 &#xff1a; 个人主页 &#x1f525;个人专栏 &#xff1a; Java编程秘籍 &#x1f304; 莫道桑榆晚&#xff0c;为霞尚满天&#xff01; 文章目录 &#x1f4d1;前言一、方法重载1.1 为什么要有方法重载1.2 方法重载的概念与使用1.3 方法签名 二、递归2…

小程序面试题之性能优化提高11道

1.如何实现上拉加载分页列表的性能优化 我们的功能里面有个滚动到底部加载的功能&#xff0c;优化前我们的做法是这样的&#xff1a; 大部分人面对长列表滚动的时候&#xff0c;一开始的处理方式都是这样的&#xff0c;如果数据不多&#xff0c;只有几页可能不会太暴露问题&…

在QT里使用SQLite数据库

什么是SQLite数据库&#xff1f;SQLite是一种轻量级的数据库管理系统&#xff0c;它不需要一个独立的服务器进程&#xff0c;可以被集成到应用程序中。SQLite是开源的&#xff0c;支持跨平台操作&#xff0c;并且使用非常广泛。在QT里如何使用SQLite数据库呢&#xff1f;废话不…

软考高级架构师:随机函数模型

一、AI 讲解 随机函数模型是理解各种随机过程和算法的一个重要概念&#xff0c;在软件工程、算法设计以及系统分析中有着广泛的应用。简而言之&#xff0c;随机函数模型是一种用于描述具有随机性的系统或过程的数学模型&#xff0c;它能够帮助我们预测和分析在不确定性下的系统…

吴恩达2022机器学习专项课程(一) 5.5 特征缩放1 5.6 特征缩放2

问题预览/关键词 什么是特征缩放&#xff1f;作用是什么&#xff1f;特征尺度和参数w权重的关系是&#xff1f;算法为什么要调节w权重&#xff1f;不进行特征缩放对梯度下降的影响&#xff1f;有特征缩放对梯度下降的影响&#xff1f;实现特征缩放的三种方法是&#xff1f;如何…

JetBrains IntelliJ IDEA 2024.1 发布 - 领先的 Java 和 Kotlin IDE

JetBrains IntelliJ IDEA 2024.1 发布 - 领先的 Java 和 Kotlin IDE 请访问原文链接&#xff1a;JetBrains IntelliJ IDEA 2024.1 (macOS, Linux, Windows) - 领先的 Java 和 Kotlin IDE&#xff0c;查看最新版。原创作品&#xff0c;转载请保留出处。 作者主页&#xff1a;s…

sqlmap一些常用命令

仅供交流学习使用&#xff0c;请勿用于非法用途 1&#xff09;检测url存在漏洞情况&#xff1a;python sqlmap.py -u "http://192.168.88.128/sqli-labs-master/Less-1/?id1" 2&#xff09;获取所有数据库名称&#xff1a;python sqlmap.py -u "http://192.168…

达梦数据库导入导出工具dmfldr

达梦数据库导入导出工具dmfldr 基础信息 OS版本&#xff1a; Red Hat Enterprise Linux Server release 7.9 (Maipo) DB版本&#xff1a; DM Database Server 64 V8 DB Version: 0x7000c 03134284132-20240115-215128-200811 dmfldr工具介绍 dmfldr&#xff08;DM Fast Loade…

大厂Java笔试题之统计兔子出生问题

题目&#xff1a;有一种兔子&#xff0c;从出生后第3个月起每个月都生一只兔子&#xff0c;小兔子长到第三个月后每个月又生一只兔子。 例子&#xff1a;假设一只兔子第3个月出生&#xff0c;那么它第5个月开始会每个月生一只兔子。 一月的时候有一只兔子&#xff0c;假如兔子…

ip addr和ifconfig区别

ip addr和ifconfig都是用于配置和管理网络接口的工具 1. ifconfig ifconfig是较旧的网络配置工具&#xff0c;属于net-tools套件的一部分。 该命令主要用于配置、显示和控制网络接口的参数&#xff0c;如IP地址、子网掩码、广播地址等。 ifconfig命令的功能相对有限&#xff…

设计模式之责任链讲解

责任链模式适用于需要将请求和处理解耦的场景&#xff0c;同时又需要动态地组织处理逻辑的场景。 通过使用责任链模式&#xff0c;可以实现请求的动态处理、灵活的扩展和简化的代码编写&#xff0c;提高系统的可维护性和可扩展性。 一、责任链入门 以下这是GPT生成的责任链代…

(三)PostgreSQL的pg_ctl命令

PostgreSQL的pg_ctl命令 pg_ctl 是 PostgreSQL 用于控制数据库服务器进程的命令行工具。它提供了启动、停止、重启数据库服务器以及管理其运行状态的手段。pg_ctl 命令尤其适用于从命令行或脚本中管理 PostgreSQL 服务&#xff0c;而不是通过操作系统的服务控制管理器。 基础…

css 太极图案例带来的收获

基础知识 渐变&#xff1a;gradient 在两个或者多个颜色之间显示平稳过度。由浏览器生成。 线性渐变&#xff1a;line-gradient(过渡方向&#xff0c;初始颜色&#xff0c;结束颜色)。注意过渡方向默认从上到下。 1、支持多颜色渐变&#xff0c;多个值&#xff0c;就是从多个…

Springboot整合物联网IOT的MQTT协议

准备工作 (下载EMQX服务端&#xff0c;相关客户端工具) 1. 服务端工具&#xff1a; https://www.emqx.io/downloads?osWindows 2. 客户端工具&#xff1a; https://mqttx.app/zh#download <!--web依赖--><dependency><groupId>org.springframework.boot…

UnityShader学习计划

1.安装ShaderlabVS,vs的语法提示 2. 常规颜色是fixed 3.FrameDebugger调试查看draw的某一帧的全部信息&#xff0c;能看到变量参数的值

架构设计-权限系统之权限系统设计

系统设计权限系统 权限管控可以通俗的理解为权力限制&#xff0c;即不同的人由于拥有不同权力&#xff0c;他所看到的、能使用的可能不一样。对应到一个应用系统&#xff0c;其实就是一个用户可能拥有不同的数据权限&#xff08;看到的&#xff09;和操作权限&#xff08;使用…

前 5 名 iPhone 数据恢复软件评测

如今&#xff0c;我们似乎将整个生活都放在手机和移动设备上。他们用许多照片、备忘录、日历日期等记录了我们的生活&#xff0c;我们总是假设这些信息在我们需要时随时可以访问。但是&#xff0c;有许多情况会导致iPhone上的数据丢失&#xff0c;例如iPhone被盗&#xff0c;损…

JVM垃圾回收(GC)

目录 目录 1.GC 简介 1.1. 引言 1.2. 何为 GC 1.2.1. 手动 GC 1.2.2. 自动 GC 引用计数法 标记清除 2.GC入门分析 2.1.碎片整理 1)对象创建时&#xff0c;执行写入操作越来越耗时 2&#xff09;内存分配错误 2.2. 分代设想 2.3. 对象分配 对象内存分配过程 2.4. …

数据中心可视化平台:有效提升运维效率与管理水平

随着企业信息化建设的不断深入&#xff0c;数据中心作为支撑企业核心业务的重要基石&#xff0c;其运维管理的复杂性和挑战性也日益凸显。为了提升数据中心机房的管理水平和效率&#xff0c;实现精细化、专业化、规范化和自动化管理&#xff0c;构建数据中心可视化平台成为了一…

【鸿蒙开发】第二十章 Camera相机服务

1 简介 开发者通过调用Camera Kit(相机服务)提供的接口可以开发相机应用&#xff0c;应用通过访问和操作相机硬件&#xff0c;实现基础操作&#xff0c;如预览、拍照和录像&#xff1b;还可以通过接口组合完成更多操作&#xff0c;如控制闪光灯和曝光时间、对焦或调焦等。 2 …