力扣:回溯算法

組合I?

class Solution {List<List<Integer>> result = new ArrayList(); // 所有結果集List<Integer> list = new ArrayList(); // 當前結果集public List<List<Integer>> combine(int n, int k) {dfs(n, k, 1);return result;}public void dfs(int n, int k, int index) {if (list.size() == k) { // 當前結果集等于要收集的數量即可存入最終結果集List<Integer> tem = new ArrayList(list);result.add(tem);return;}for (int i = index; i <= n; i++) {list.add(i); // 元素加入當前結果集dfs(n, k, i + 1); // 遞歸list.remove(list.size() - 1); // 該元素組合完成可以移除(回溯)}}
}

組合II?

class Solution {List<List<Integer>> result = new ArrayList(); // 所有結果集Set<List<Integer>> set = new HashSet(); // 結果集去重List<Integer> list = new ArrayList(); // 當前結果集public List<List<Integer>> combinationSum2(int[] candidates, int target) {backTring(candidates, 0, target, 0);return result;}public void backTring(int[] candidates, int sum, int target, int index) {if (candidates == null || candidates.length < 0) return; if (sum == target) { // 總和等于目標值是返回當前結果集List<Integer> tem = new ArrayList(list);Collections.sort(tem); // 去重(如:1 1 2 和 2 1 1 是一組結果集)if (!set.contains(tem)) { result.add(new ArrayList(list));set.add(tem);}return;}if (sum > target) { // 當前結果集大于目標值說明當前結果集不對return;}for (int i = index; i < candidates.length; i++) {sum += candidates[i]; // 當前總和list.add(candidates[i]); // 當前結果集backTring(candidates, sum, target, i + 1);sum -= candidates[i]; // 回溯總和list.remove(list.size() - 1); // 回溯結果集}}
}

?組合III

class Solution {List<List<Integer>> result = new ArrayList(); // 最終結果集List<Integer> list = new ArrayList(); // 當前結果集public List<List<Integer>> combinationSum3(int k, int n) {backCheck(k, n, 1, 0, 0);return result;}public void backCheck(int k, int n, int num, int count, int sum) {if (count == k && n == sum) { // 元素數量等于k 且 sum等于 n 時為符合的結果集result.add(new ArrayList(list));return;}if (count > k || n < sum) { // 要求的數量或者總和不對則返回return;}for (int i = num; i <= 9; i++) {list.add(i);sum += i;count++;backCheck(k, n, i + 1, count, sum);list.remove(list.size() - 1);sum -= i;count--;}}
}

?分割回文串

class Solution {List<List<String>> result = new ArrayList(); // 最終結果集List<String> list = new ArrayList(); // 當前結果集public String[][] partition(String s) {int n = s.length();dfs(0, n, s);return listToArrays(result); // 集合轉換為數組}public void dfs(int index, int n, String s) {if (index == n) { // 指針指向n時說明遍歷到字符串末尾,可以返回結果集result.add(new ArrayList(list));return;}for (int i = index; i < n; i++) {if (isPalindrome(s.substring(index, i + 1))) {  // 如果是回文串則加入當前結果集         list.add(s.substring(index, i + 1)); // 加入結果集dfs(i + 1, n, s);list.remove(list.size() - 1); // 回溯}}}public boolean isPalindrome(String str) { // 判斷是否為回文串int l = 0;int r = str.length() - 1;while (l < r) {if (str.charAt(l) != str.charAt(r)) {return false;}l++;r--;}return true;}public String[][] listToArrays (List<List<String>> list) { // 集合轉換為數組int n = list.size();String[][] arrs = new String[n][];for (int i = 0; i < n; i++) {List<String> tem = list.get(i);String[] arr = tem.toArray(new String[tem.size()]);arrs[i] = arr;}return arrs;}
}

復原 IP 地址

class Solution {List<String> res = new ArrayList(); // 所有結果集List<String> tem = new ArrayList(); // 當前結果集public List<String> restoreIpAddresses(String s) {int n = s.length(); // 字符串長度if (n < 0 || n > 12) return res; // 剪枝dfs(s, 0, n);return res;}public void dfs(String s, int index, int n) {if (tem.size() == 4) { // ip地址為四個數字組成,當前結果集等于4即可返回if (index == n) { // 當前指針指向末尾即可加入最終結果集StringBuilder sb = new StringBuilder(); // 拼湊成需要的字符串for (int i = 0; i < 4; i++) {sb.append(tem.get(i));if (i != 3) {sb.append(".");}}res.add(sb.toString()); // 加入到最終結果集}return;}for (int i = index; i < n && i < index + 3; i++) { // 當前指針if (isNum(s.substring(index, i + 1))) { //tem.add(s.substring(index, i + 1));dfs(s, i + 1, n);tem.remove(tem.size() - 1);}}}public boolean isNum(String s) { // 判斷是否為合法數字if (s.length() >= 2 && s.charAt(0) == '0') return false;Integer num = Integer.valueOf(s);if (num > 255) return false;return true;}
}

子集I

class Solution {List<List<Integer>> res = new ArrayList();List<Integer> tem = new ArrayList();public List<List<Integer>> subsets(int[] nums) {dfs(nums, 0, nums.length);return res;}public void dfs(int[] nums, int index, int n) {res.add(new ArrayList(tem)); // 每次遞歸都是一個新子集for (int i = index; i < n; i++) {tem.add(nums[i]);dfs(nums, i + 1, n);tem.remove(tem.size() - 1);}}
}

?子集II

class Solution {List<List<Integer>> res = new ArrayList(); // 所有結果集List<Integer> list = new ArrayList(); // 當前子集Set<List<Integer>> set = new HashSet();  // 子集去重public List<List<Integer>> subsetsWithDup(int[] nums) {Arrays.sort(nums); // 排序dfs(nums, 0, nums.length);return res;}public void dfs(int[] nums, int index, int n) {res.add(new ArrayList(list)); // 每次遞歸都是新子集for (int i = index; i < n; i++) {if (i != index && nums[i] == nums[i - 1]) continue; // 數組已經排序,如果當前元素等于上一個元素進行遞歸會有重復子集(如:數組 {1 1} 的子集為 {1} {1 1},如果索引到第二個元素再進行遞歸則會有重復子集{1}list.add(nums[i]); dfs(nums, i + 1, n);list.remove(list.size() - 1);}}
}

?最長遞增子序列

?

class Solution {public int lengthOfLIS(int[] nums) {int[] dp = new int[nums.length]; // 動態規劃+暴力枚舉Arrays.fill(dp, 1); // 每個子序列起始都是1int max = dp[0];for (int i = 1; i < nums.length; i++) {for (int j = 0; j < i; j++) { // 判斷當前位置最長子序列是多少if (nums[j] < nums[i]) {dp[i] = Math.max(dp[i], dp[j] + 1);}}max = max > dp[i] ? max : dp[i];}return max;}
}

全排列I

class Solution {List<List<Integer>> res = new ArrayList(); // 所有結果集List<Integer> list = new ArrayList(); // 當前結果集public List<List<Integer>> permute(int[] nums) {boolean[] used = new boolean[nums.length]; // 判斷當前元素是否加入結果集dfs(nums, used);return res;}public void dfs(int[] nums, boolean[] used) {if (list.size() == nums.length) { // 當前結果集長度等于數組長度即可加入所有結果集res.add(new ArrayList(list));}for (int i = 0; i < nums.length; i++) {if (used[i] == false) { // 判斷元素是否加入當前結果集list.add(nums[i]); // 元素入集合used[i] = true; // 設置元素狀態為被使用dfs(nums, used);used[i] = false; // 回溯list.remove(list.size() - 1);}}}
}

?全排列II

class Solution {List<List<Integer>> res = new ArrayList(); // 所有結果集合List<Integer> list = new ArrayList(); // 當前結果集合Set<List<Integer>> set = new HashSet(); // 結果集去重public List<List<Integer>> permuteUnique(int[] nums) {boolean[] flag = new boolean[nums.length]; // 判斷元素是否加入當前結果集dfs(nums, flag);return res;}public void dfs(int[] nums, boolean[] flag) {if (list.size() == nums.length) { // 當前結果集合等于數組長度即可加入最終結果集List<Integer> tem = new ArrayList(list);if (!set.contains(tem)) { // 判斷該結果集是否在最終結果集中存在set.add(tem); // 該結果集的順序存入去重集合中,避免重復加入最終結果集res.add(tem);}}for (int i = 0; i < nums.length; i++) {if (flag[i] == false) {list.add(nums[i]);flag[i] = true;dfs(nums, flag);flag[i] = false;list.remove(list.size() - 1);}}}
}

?N皇后

class Solution {List<List<String>> res = new ArrayList(); // 最終結果集合List<String> list = new ArrayList(); // public List<List<String>> solveNQueens(int n) {char[][] board = new char[n][n]; // 創建棋盤并初始化for (int i = 0; i < n; i++) {for (int j = 0; j < n; j++) {board[i][j] = '.';}}dfs(board, n, 0);return res;}public void dfs(char[][] board, int n, int row) {if (row == n) { // 當第row行也可以放棋子說明該方法合法res.add(printResult(board, n));return;}for (int col = 0; col < n; col++) {// 判斷該位置是否可以填棋if (isFlag(board, row, col)) {board[row][col] = 'Q';dfs(board, n, row + 1);board[row][col] = '.';}}}// 核心方法判斷棋子放置位置是否合法public boolean isFlag(char[][] board, int row, int col) { // 判斷該位置放棋子是否合法int n = board.length;for (int i = 0; i < n; i++) { // 同一列不能有皇后if (board[i][col] == 'Q') return false;}for (int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) { // 右斜線不能有皇后if (board[i][j] == 'Q') return false;}for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) { // 左斜線不能有皇后if (board[i][j] == 'Q') return false;}return true; // 合法}public List<String> printResult(char[][] board, int n) { // 按照題目要求打印結果集List<String> list = new ArrayList();for (int i = 0; i < n; i++) {StringBuilder sb = new StringBuilder();for (int j = 0; j < n; j++) {sb.append(board[i][j]);}list.add(sb.toString());}return list;}
}

?解數獨

class Solution {public void solveSudoku(char[][] board) {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 (char c = '1'; c <= '9'; c++) {if (isFlag(board, i, j, c)) {board[i][j] = c; // 暫時填充該數字if (dfs(board)) return true;board[i][j] = '.'; // 遞歸到后面不合法,回溯}}return false;}}}return true;}// 核心方法,判斷該位置的數字是否合法public boolean isFlag(char[][] board, int row, int col, char c) { // 判斷該數字是否重復for (int i = 0; i < 9; i++) {// 同行出現過if (board[i][col] == c) return false; // 同列出現過if (board[row][i] == c) return false; // 九宮格出現過if (board[(row / 3) * 3 + i / 3][(col / 3) * 3 + i % 3] == c) return false;}return true;}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/74672.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/74672.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/74672.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

華為HCIE鴻蒙應用開發認證靠譜嗎?

在萬物互聯時代&#xff0c;智能終端設備的多樣性與協同需求催生了操作系統的革新。華為HarmonyOS&#xff08;鴻蒙系統&#xff09;憑借其分布式架構與全場景能力&#xff0c;正成為打破設備邊界、重塑用戶體驗的核心技術底座。HCIE鴻蒙應用開發認證作為華為認證體系的頂級資質…

23種設計模式-原型(Prototype)設計模式

原型設計模式 &#x1f6a9;什么是原型設計模式&#xff1f;&#x1f6a9;原型設計模式的特點&#x1f6a9;原型設計模式的結構&#x1f6a9;原型設計模式的優缺點&#x1f6a9;原型設計模式的Java實現&#x1f6a9;代碼總結&#x1f6a9;總結 &#x1f6a9;什么是原型設計模式…

Oracle-rman restore遭遇RMAN-03002與ORA-19563

文章目錄 在原DB上檢查是否有重復的文件名&#xff1a;查看rman恢復的日志修正重名部分重新執行rman恢復結論&#xff1a; 在 RMAN 恢復過程中&#xff0c;遇到RMAN-03002連同ORA-19563:錯誤。 操作是將 Oracle 10.0.5的數據庫備份從 RMAN備份恢復到另一臺測試主機的同一個目錄…

運維網絡排查工具介紹與使用

作為一名運維工程師&#xff0c;日常工作中最令人頭疼的莫過于各種網絡故障。在過去一年半的運維生涯中&#xff0c;我積累了豐富的網絡故障排查經驗&#xff0c;今天就來和大家分享一下如何運用抓包工具&#xff08;Wireshark、tcpdump&#xff09;和網絡排查工具&#xff08;…

解決vscode終端和本地終端python版本不一致的問題

&#x1f33f; 問題描述 本地終端&#xff1a; vscode終端&#xff1a; 別被這個給騙了&#xff0c;繼續往下看&#xff1a; 難怪我導入一些包的時候老提示找不到&#xff0c;在本地終端就不會這樣&#xff0c;于是我嚴重懷疑vscode中的python版本和終端不一樣&#xff0c…

Sublime全局搜索快捷鍵Ctrl+Shift+F不能使用解決

問題描述&#xff1a; 在安裝好Sublime后&#xff0c;我們使用快捷鍵進行全局搜索&#xff0c;發現沒有反應&#xff0c;但是中文輸入變成了繁體。 解決方案&#xff1a; 如截圖&#xff0c;在關閉簡繁切換的快捷鍵或者換成其他的就行

海康HTTP監聽報警事件數據

http監聽接收報警事件數據 海康獲取設備報警事件數據兩種方式&#xff1a; 1、sdk 布防監聽報警事件數據,服務端布防。&#xff08;前面文章有示例&#xff09; 2、http監聽接收報警事件數據&#xff0c;設備直接推送。 http監聽接收報警事件數據&#xff0c;服務端可以使用n…

Python----計算機視覺處理(Opencv:圖像邊緣檢測:非極大值抑制,雙閾值篩選)

一、 高斯濾波 邊緣檢測本身屬于銳化操作&#xff0c;對噪點比較敏感&#xff0c;所以需要進行平滑處理。這里使用的是一個5*5的高斯 核對圖像進行消除噪聲。 二、計算圖像的梯度和方向 三、非極大值抑制 在得到每個邊緣的方向之后&#xff0c;其實把它們連起來邊緣檢測就算完了…

Maven工具學習使用(四)——倉庫

倉庫分類 對于Mavne來說,倉庫只分為兩類:本地倉庫和遠程倉庫。當Maven根據坐標查詢尋找構件的時候,它首先會查看本地倉庫,如果本地倉庫存在此構件,則直接使用;如果本地倉庫不存在此構件,或者需要查看是否有更新的構件版本,Maven就會去遠程倉庫查找,發現需要的構件之后…

Axure PR 9.0(發音:Ack-sure)原型圖工具入門教程:鏈接交互

文章目錄 引言Axure? RP 9I Axure RP9入門介紹元件庫對兩個元件進行連接頁面:導航視圖、概要母版交互II 鏈接交互從A頁面跳轉到B頁面返回之前的頁面see also引言 【 產品原型圖】核心價值和實際應用場景:可視化需求,統一團隊理解 https://blog.csdn.net/z929118967/articl…

docker遠程debug

1. 修改 Java 啟動命令 在 Docker 容器中啟動 Java 程序時&#xff0c;需要添加 JVM 調試參數&#xff0c;jdk8以上版本 java -agentlib:jdwptransportdt_socket,servery,suspendn,address*:5005 -jar your-app.jar jdk8及以下版本&#xff1a; java -Xdebug -Xrunjdwp:tra…

K8S學習之基礎五十四:jenkins新建測試流水線

jenkins新建測試流水線 新建任務 node(testak) {stage(第1步:從gitee上下載源代碼) {git url: "https://gitee.com/akang007/jenkins-sample"script {build_tag sh(returnStdout: true, script: git rev-parse --short HEAD).trim()}}stage(第2步&#xff1a;基…

SylixOS 中 select 原理及使用分析

1、select接口簡介 1.1 select接口使用用例 select 是操作系統多路 I/O 復用技術實現的方式之一。 select 函數允許程序監視多個文件描述符&#xff0c;等待所監視的一個或者多個文件描述符變為“準備好”的狀態。所謂的”準備好“狀態是指&#xff1a;文件描述符不再是阻塞狀…

Spring WebFlux之ServerWebExchange

ServerWebExchange 是 Spring WebFlux 中的一個核心接口&#xff0c;用于表示服務器端處理的 HTTP 請求和響應。它封裝了請求和響應的所有信息&#xff0c;并提供了相應的方法來操作這些信息。ServerWebExchange 在響應式編程模型中扮演著關鍵角色&#xff0c;支持非阻塞、異步…

Flutter 常見錯誤和坑

1. 狀態管理問題 StatefulWidget 生命周期誤用 // 錯誤&#xff1a;在 build 方法中修改狀態 override Widget build(BuildContext context) {setState(() { counter; }); // 會導致無限重建循環return Text($counter); }// 正確&#xff1a;在事件處理中修改狀態 Widget bui…

C++智能指針萬字詳細講解(包含智能指針的模擬實現)

在筆試&#xff0c;面試中智能指針經常出現&#xff0c;如果你對智能指針的作用&#xff0c;原理&#xff0c;用法不了解&#xff0c;那么可以看看這篇博客講解&#xff0c;此外本博客還簡單模擬實現了各種指針&#xff0c;在本篇的最后還應對面試題對智能指針的知識點進行了拓…

【Go】Go語言結構體筆記

整體介紹 雖然 Go 語言不是傳統意義上的面向對象語言&#xff0c;但它提供了結構體&#xff08;struct&#xff09;來組織數據&#xff0c;并且可以為結構體綁定方法&#xff0c;從而達到面向對象的部分效果。 關鍵知識點包括&#xff1a; 結構體定義與實例化 定義結構體時使用…

Three.js 快速入門教程【十八】射線拾取模型——鼠標點擊屏幕選中模型或物體

系列文章目錄 Three.js 快速入門教程【一】開啟你的 3D Web 開發之旅 Three.js 快速入門教程【二】透視投影相機 Three.js 快速入門教程【三】渲染器 Three.js 快速入門教程【四】三維坐標系 Three.js 快速入門教程【五】動畫渲染循環 Three.js 快速入門教程【六】相機控件 Or…

Object.defineProperty()Proxy詳解(Vue23數據劫持實現)

底層原理&#x1f447;&#x1f3ff; 總結一下&#xff0c;結構應該包括&#xff1a; 1. 方法的基本作用和參數。 2. 數據描述符和存取描述符的區別。 3. 屬性定義的內部處理流程。 4. 在Vue中的應用實例。 5. 常見錯誤和正確實踐。 每個部分都要結合搜索結果的信息&…

MySQL 進階語法:函數、約束、多表查詢、事務

目錄 一、MySQL 常用函數 1. 字符串函數 1.1 基本字符串操作 1.2 字符串截取與處理 1.3 字符串搜索與替換 2. 數值函數 2.1 基本數學運算 2.2 數學計算 2.3 隨機數與符號 3. 日期時間函數 3.1 獲取當前時間 3.2 日期時間計算 3.3 日期時間提取 3.4 日期時間格式化…