31.递归、搜索、回溯之综合练习

1.找出所有子集的异或总和再求和(easy)

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {int path;int sum;public int subsetXORSum(int[] nums) {dfs(nums, 0);return sum;}public void dfs(int[] nums, int pos) {sum += path;for (int i = pos; i < nums.length; i++) {path ^= nums[i];dfs(nums, i + 1);path ^= nums[i]; // 恢复现场}}
}

2.全排列2

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {List<Integer> path;List<List<Integer>> ret;boolean[] check;public List<List<Integer>> permuteUnique(int[] nums) {path = new ArrayList<>();ret = new ArrayList<>();check = new boolean[nums.length];Arrays.sort(nums);dfs(nums, 0);return ret;}public void dfs(int[] nums, int pos) {if (pos == nums.length) {ret.add(new ArrayList<>(path));return;}for (int i = 0; i < nums.length; i++) {// 剪枝if (check[i] == false && (i == 0 || nums[i] != nums[i - 1] ||check[i - 1] != false)) {path.add(nums[i]);check[i] = true;dfs(nums, pos + 1);// 回溯 -> 恢复现场path.remove(path.size() - 1);check[i] = false;}}}
}

3.电话号码的字母组合(medium)

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {String[] hash = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv","wxyz" };List<String> ret;StringBuffer path;public List<String> letterCombinations(String digits) {ret = new ArrayList<>();path = new StringBuffer();if (digits.length() == 0)return ret;dfs(digits, 0);return ret;}public void dfs(String digits, int pos) {if (pos == digits.length()) {ret.add(path.toString());return;}String cur = hash[digits.charAt(pos) - '0'];for (int i = 0; i < cur.length(); i++) {path.append(cur.charAt(i));dfs(digits, pos + 1);path.deleteCharAt(path.length() - 1); // 恢复现场}}
}

4.括号生成

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {int left, right, n;StringBuffer path;List<String> ret;public List<String> generateParenthesis(int _n) {n = _n;path = new StringBuffer();ret = new ArrayList<>();dfs();return ret;}public void dfs() {if (right == n) {ret.add(path.toString());return;}if (left < n) // 添加左括号{path.append('(');left++;dfs();path.deleteCharAt(path.length() - 1);left--; // 恢复现场}if (right < left) // 添加哎右括号{path.append(')');right++;dfs();path.deleteCharAt(path.length() - 1);right--; // 恢复现场}}
}

5.组合

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {List<Integer> path;List<List<Integer>> ret;int n, k;public List<List<Integer>> combine(int _n, int _k) {n = _n;k = _k;path = new ArrayList<>();ret = new ArrayList<>();dfs(1);return ret;}public void dfs(int start) {if (path.size() == k) {ret.add(new ArrayList<>(path));return;}for (int i = start; i <= n; i++) {path.add(i);dfs(i + 1);path.remove(path.size() - 1); // 恢复现场}}
}

6.目标和

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution{int ret, aim;public int findTargetSumWays(int[] nums, int target) {aim = target;dfs(nums, 0, 0);return ret;}public void dfs(int[] nums, int pos, int path){if(pos == nums.length){if(path == aim) ret++;return;}// 加法dfs(nums, pos + 1, path + nums[pos]);// 减法dfs(nums, pos + 1, path - nums[pos]);}
}

7.组合总和

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {int aim;List<Integer> path;List<List<Integer>> ret;public List<List<Integer>> combinationSum(int[] nums, int target) {path = new ArrayList<>();ret = new ArrayList<>();aim = target;dfs(nums, 0, 0);return ret;}public void dfs(int[] nums, int pos, int sum) {if (sum == aim) {ret.add(new ArrayList<>(path));return;}if (sum > aim || pos == nums.length)return;// 枚举 nums[pos] 使⽤多少个for (int k = 0; k * nums[pos] + sum <= aim; k++) {if (k != 0)path.add(nums[pos]);dfs(nums, pos + 1, sum + k * nums[pos]);}// 恢复现场for (int k = 1; k * nums[pos] + sum <= aim; k++) {path.remove(path.size() - 1);}}
}

8.字母大小写全排列

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {StringBuffer path;List<String> ret;public List<String> letterCasePermutation(String s) {path = new StringBuffer();ret = new ArrayList<>();dfs(s, 0);return ret;}public void dfs(String s, int pos) {if (pos == s.length()) {ret.add(path.toString());return;}char ch = s.charAt(pos);// 不改变path.append(ch);dfs(s, pos + 1);path.deleteCharAt(path.length() - 1); // 恢复现场// 改变if (ch < '0' || ch > '9') {char tmp = change(ch);path.append(tmp);dfs(s, pos + 1);path.deleteCharAt(path.length() - 1); // 恢复现场}}public char change(char ch) {if (ch >= 'a' && ch <= 'z')return ch -= 32;elsereturn ch += 32;}
}

9.优美的排列

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {boolean[] check;int ret;public int countArrangement(int n) {check = new boolean[n + 1];dfs(1, n);return ret;}public void dfs(int pos, int n) {if (pos == n + 1) {ret++;return;}for (int i = 1; i <= n; i++) {if (check[i] == false && (i % pos == 0 || pos % i == 0)) {check[i] = true;dfs(pos + 1, n);check[i] = false; // 恢复现场}}}
}

10.N皇后

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {boolean[] checkCol, checkDig1, checkDig2;List<List<String>> ret;char[][] path;int n;public List<List<String>> solveNQueens(int _n) {n = _n;checkCol = new boolean[n];checkDig1 = new boolean[n * 2];checkDig2 = new boolean[n * 2];ret = new ArrayList<>();path = new char[n][n];for (int i = 0; i < n; i++)Arrays.fill(path[i], '.');dfs(0);return ret;}public void dfs(int row) {if (row == n) {// 添加结果List<String> tmp = new ArrayList<>();for (int i = 0; i < n; i++) {tmp.add(new String(path[i]));}ret.add(new ArrayList<>(tmp));}for (int col = 0; col < n; col++) {// 判断能不能放if (checkCol[col] == false && checkDig1[row - col + n] == false &&checkDig2[row + col] == false) {path[row][col] = 'Q';checkCol[col] = checkDig1[row - col + n] = checkDig2[row +col] = true;dfs(row + 1);// 恢复现场path[row][col] = '.';checkCol[col] = checkDig1[row - col + n] = checkDig2[row +col] = false;}}}
}

11.有效的数独

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {boolean[][] row, col;boolean[][][] grid;public boolean isValidSudoku(char[][] board) {row = new boolean[9][10];col = new boolean[9][10];grid = new boolean[3][3][10];for (int i = 0; i < 9; i++)for (int j = 0; j < 9; j++) {if (board[i][j] != '.') {int num = board[i][j] - '0';// 是否有效if (row[i][num] || col[j][num] || grid[i / 3][j / 3][num])return false;row[i][num] = col[j][num] = grid[i / 3][j / 3][num] = true;}}return true;}
}

12.解数独

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {boolean[][] row, col;boolean[][][] grid;public void solveSudoku(char[][] board) {row = new boolean[9][10];col = new boolean[9][10];grid = new boolean[3][3][10];// 初始化for (int i = 0; i < 9; i++)for (int j = 0; j < 9; j++)if (board[i][j] != '.') {int num = board[i][j] - '0';row[i][num] = col[j][num] = grid[i / 3][j / 3][num] = true;}dfs(board);}public boolean dfs(char[][] board) {for (int i = 0; i < 9; i++) {for (int j = 0; j < 9; j++) {if (board[i][j] == '.') {// 填数for (int num = 1; num <= 9; num++) {// 剪枝if (!row[i][num] && !col[j][num] && !grid[i / 3][j / 3][num]) {board[i][j] = (char) ('0' + num);row[i][num] = col[j][num] = grid[i / 3][j / 3][num] = true;if (dfs(board) == true)return true; // 重点理解// 恢复现场board[i][j] = '.';row[i][num] = col[j][num] = grid[i / 3][j / 3][num] = false;}}return false; // 重点理解}}}return true; // 重点理解}
}

13.单词搜索

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {boolean[][] vis;int m, n;char[] word;public boolean exist(char[][] board, String _word) {m = board.length;n = board[0].length;word = _word.toCharArray();vis = new boolean[m][n];for (int i = 0; i < m; i++)for (int j = 0; j < n; j++) {if (board[i][j] == word[0]) {vis[i][j] = true;if (dfs(board, i, j, 1))return true;vis[i][j] = false;}}return false;}int[] dx = { 0, 0, 1, -1 };int[] dy = { 1, -1, 0, 0 };public boolean dfs(char[][] board, int i, int j, int pos){if(pos == word.length){return true;}// 上下左右去匹配 word[pos]// 利⽤向量数组,⼀个 for 搞定上下左右四个⽅向for(int k = 0; k < 4; k++){int x = i + dx[k], y = j + dy[k];if(x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && board[x][y]== word[pos]){vis[x][y] = true;if(dfs(board, x, y, pos + 1)) return true;vis[x][y] = false;}}return false;}
}

14.黄金矿工

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {boolean[][] vis;int m, n;int[] dx = { 0, 0, -1, 1 };int[] dy = { 1, -1, 0, 0 };int ret;public int getMaximumGold(int[][] g) {m = g.length;n = g[0].length;vis = new boolean[m][n];for (int i = 0; i < m; i++)for (int j = 0; j < n; j++) {if (g[i][j] != 0) {vis[i][j] = true;dfs(g, i, j, g[i][j]);vis[i][j] = false;}}return ret;}public void dfs(int[][] g, int i, int j, int path) {ret = Math.max(ret, path);for (int k = 0; k < 4; k++) {int x = i + dx[k], y = j + dy[k];if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && g[x][y] != 0) {vis[x][y] = true;dfs(g, x, y, path + g[x][y]);vis[x][y] = false;}}}
}

15.不同路径3

. - 力扣(LeetCode)

题目解析

算法原理

代码

class Solution {boolean[][] vis;int m, n, step;int ret;int[] dx = { 0, 0, 1, -1 };int[] dy = { 1, -1, 0, 0 };public int uniquePathsIII(int[][] grid) {m = grid.length;n = grid[0].length;vis = new boolean[m][n];int bx = 0, by = 0;for (int i = 0; i < m; i++)for (int j = 0; j < n; j++)if (grid[i][j] == 0)step++;else if (grid[i][j] == 1) {bx = i;by = j;}step += 2;vis[bx][by] = true;dfs(grid, bx, by, 1);return ret;}public void dfs(int[][] grid, int i, int j, int count) {if (grid[i][j] == 2) {if (count == step) {ret++;}return;}for (int k = 0; k < 4; k++) {int x = i + dx[k], y = j + dy[k];if (x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && grid[x][y] != -1) {vis[x][y] = true;dfs(grid, x, y, count + 1);vis[x][y] = false;}}}
}

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

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

Vue(12)——路由的基本使用

VueRouter 作用&#xff1a;修改地址栏路径时&#xff0c;切换显示匹配的组件 基本步骤&#xff08;固定&#xff09; 下载&#xff1a;下载VueRouter模块到当前工程引入安装注册创建路由对象注入&#xff0c;将路由对象注入到new Vue 实例中&#xff0c;建立关联 发现了#/表…

『功能项目』事件中心处理怪物死亡【55】

我们打开上一篇54回调函数处理死亡的项目&#xff0c; 本章要做的事情是用事件中心处理怪物死亡后的逻辑 首先打开之前事件中心脚本&#xff08;不做更改&#xff0c;调用即可&#xff09;&#xff1a; using System.Collections.Generic; using UnityEngine.Events; //中介者…

fiddler抓包04_基础设置(字体/工具栏/抓包开关/清空)

课程大纲 1. 设置字体 菜单栏 “工具”&#xff08;tool&#xff09; - “选项”&#xff08;options&#xff09; - “appearance”&#xff0c;设置字号和字体后&#xff0c;点击确认&#xff0c;立刻生效&#xff08;无需重启&#xff09;。 2. 展开/收起工具栏 菜单栏 “…

MySQL 事件调度器用法解析

MySQL 事件调度器用法解析 在日常的数据库运维与开发实践中&#xff0c;自动化执行任务是一项至关重要的需求&#xff0c;它极大地提升了数据库管理的效率和准确性。这些任务可能包括清理不再需要的历史数据以释放存储空间、更新汇总或统计信息以保持数据的新鲜度&#xff0c;…

【两方演化博弈代码复现】:双方演化博弈的原理、概率博弈仿真、相位图、单个参数灵敏度演化

目录-基于MatLab2016b实现 一、演化博弈的原理1. 基本概念2. 参与者的策略3.演化过程 二、MATLAB 代码解读&#xff08;博弈参与主体&#xff08;双方&#xff09;策略选择的动态演化讨程&#xff09;三、MATLAB 代码解读&#xff08;博弈主体随着时间策略选择的动态演化讨程&a…

启动windows更新/停止windows更新,电脑自动更新怎么彻底关闭?如何操作?

关于启动Windows更新、停止Windows更新以及彻底关闭电脑自动更新的问题&#xff0c;以下是根据专业角度提供的详细指导&#xff1a; 启动Windows更新 1.通过Windows设置启动更新&#xff1a; -点击开始菜单&#xff0c;选择“设置”&#xff08;或使用快捷键WinI&a…

YOLOv8 的安装与训练

YOLOv8 是 YOLO 系列实时目标检测器中的较新迭代版本&#xff0c;在准确性和速度方面提供了前沿性能。基于之前 YOLO 版本的进步&#xff0c;YOLOv8 引入了新的特性和优化&#xff0c;使其成为各种应用中各种目标检测任务的理想选择。 一、安装显卡驱动与CUDA&#xff1a; 这个…

aspcms 获取webshell漏洞复现

1.通过访问/admin_aspcms/login.asp来到后台 使用admin 123456 登录 2.点击扩展功能-幻灯片设置-保存&#xff0c;同时进行抓包 3.修改数据包中的slideTextStatus字段&#xff0c;将其更改为 1%25><%25Eval(Request (chr(65)))%25><%25 密码为a 4.访问木马的地…

可靠性:MSTP 和 VRRP 配置实验

一、拓扑&#xff1a; 说明&#xff1a; 1、交换机 SW1、2、3 分别起 vlan 10、20&#xff0c;都以 trunk 方式连接 2、 PC1、2 分别属于 vlan 10、20 3、SW1、2 起 vlan 100 做为管理段&#xff0c;网关地址分别以 100.1.1.1/24 和 200.1.1.2/24 和 AR1相连 …

【日记】对这两天的总结,比赛止步 32 强(3338 字)

正文 这两天的事情非常多&#xff0c;一直也没来得及写。 这篇日记相当于对这几天的一个大总结吧。 2024 年 9 月 13 日 - 14 日 这两天都在培训&#xff0c;所幸最终考核卷子&#xff0c;题目出得不是很难。只给半个小时考试。我的天啊&#xff0c;我题目都没写完。 我印象中出…

即时通讯平台是什么?

即时通讯平台是一种软件或服务&#xff0c;用于提供实时的多媒体沟通和交流功能。它允许用户在任何时间、任何地点&#xff0c;通过文本、语音、图片、视频等方式与其他用户进行实时的双向交流。即时通讯平台在个人和企业间广泛应用&#xff0c;为用户提供了高效便捷的沟通工具…

虚拟机centos_7 配置教程(镜像源、配置centos、静态ip地址、Finalshell远程操控使用)

文章目录 一、下载镜像源&#xff08;准备工作&#xff09;1、开源网站2、下载 二、VMware配置centos三、配置静态IP地址四、Finalshell使用1、下载Finalshell2、连接虚拟机 五、谢谢观看&#xff01; 一、下载镜像源&#xff08;准备工作&#xff09; 1、开源网站 有许多开源…

[DDCTF2018](╯°□°)╯︵ ┻━┻

贴个脚本在这 def split_and_convert(input_string):# 检查字符串长度是否为偶数if len(input_string) % 2 ! 0:print("字符串长度不是偶数&#xff0c;最后一个字符将被丢弃。")input_string input_string[:-1] # 丢弃最后一个字符# 使用列表推导式将字符串分隔为…

中位数贪心+分组,CF 433C - Ryouko‘s Memory Note

目录 一、题目 1、题目描述 2、输入输出 2.1输入 2.2输出 3、原题链接 二、解题报告 1、思路分析 2、复杂度 3、代码详解 一、题目 1、题目描述 2、输入输出 2.1输入 2.2输出 3、原题链接 433C - Ryoukos Memory Note 二、解题报告 1、思路分析 改变 x 只会影响…

47.面向对象综合训练-汽车

//题目需求&#xff1a;定义数组存储3个汽车对象 //汽车的属性&#xff1a;品牌&#xff0c;价格&#xff0c;颜色 //创建三个汽车对象&#xff0c;数据通过键盘录入而来&#xff0c;并把数据存入到数组当中 1.标准的JavaBean类 public class Car {private String brand;//品…

Ubuntu使用docker安装Oracle23aiFree

Oracle 安装docker安装部署 官网&#xff1a;Oracle23AI 功能亮点 AI战略搜索 Oracle AI Vector Search专为人工智能&#xff08;AI&#xff09;工作负载而设计&#xff0c;允许您基于语义而不是关键字查询数据。 JSON 关系二元性 数据可以作为 JSON 文档或关系表透明地访问和…

『功能项目』第二职业法师的平A【57】

我们打开上一篇56制作提示主角升级面板的项目&#xff0c; 本章要做的事情是制作法师平A的魔法球触碰到Boss后让Boss受到一个无视攻击力与防御力的一个&#xff08;100&#xff09;左右随机的一个伤害值 修改脚本&#xff1a;PlayerCtrl.cs 将法师职业生成的魔法球的标签Tag设…

2019-2023(CSP-J)选择题真题解析

1&#xff0c;了解的知识 中国的国家顶级域名是&#xff08; &#xff09;【2019年CSP-J初赛选择题第一题】 A…cn B…ch C…chn D…china 【答案】&#xff1a;A 以下哪个奖项是计算机科学领域的最高奖&#xff1f;&#xff08; &#xff09;【2019年CSP-J初赛选择题第…

项目实训:CSS基本布局理解——WEB开发系列38

对CSS学习已经接近尾声&#xff0c;下面你可以对以下两道“小卡拉米”测试进行测试下CSS理解程度。 题 1&#xff1a;基于栅格布局的现代博客首页设计 题目要求&#xff1a; 创建一个博客首页布局&#xff0c;包含一个顶部导航栏、一个主要的内容区域&#xff08;左侧为博客文…

PumpkinRaising靶机详解

靶机下载地址 https://www.vulnhub.com/entry/mission-pumpkin-v10-pumpkinraising,324/ 靶机配置 端口扫描 nmap -sV -A -T4 192.168.229.162 访问网页 http://192.168.229.162/ 查看页面源码 base64解密 发现base64解码后的信息不重要 发现一个html网页&#xff0c;访问 …