代碼隨想錄-回溯算法

在這里插入圖片描述

  1. 組合
//未剪枝
class Solution {List<List<Integer>> ans = new ArrayList<>();Deque<Integer> path = new LinkedList<>();public List<List<Integer>> combine(int n, int k) {backtracking(n, k, 1);return ans;}public void backtracking(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);backtracking(n, k, i + 1);path.removeLast();}}
}
//剪枝
class Solution {List<List<Integer>> ans = new ArrayList<>();Deque<Integer> path = new LinkedList<>();public List<List<Integer>> combine(int n, int k) {backtracking(n, k, 1);return ans;}public void backtracking(int n, int k, int startIndex) {if (path.size() == k) {ans.add(new ArrayList<>(path));return;}for (int i = startIndex; i <= n - (k - path.size()) + 1; i++) {path.add(i);backtracking(n, k, i + 1);path.removeLast();}}
}
  1. 組合總和 III
class Solution {List<List<Integer>> ans = new ArrayList<>();Deque<Integer> path = new LinkedList<>();public List<List<Integer>> combinationSum3(int k, int n) {backtracking(k, n, 0, 1);return ans;}public void backtracking(int k, int targetSum, int sum, int startIndex) {if (path.size() == k) {if (sum == targetSum) {ans.add(new ArrayList<>(path));}return;}for (int i = startIndex; i <= 9; i++) {sum += i;path.add(i);backtracking(k, targetSum, sum, i + 1);sum -= i;path.removeLast();}}
}
  1. 電話號碼的字母組合
class Solution {List<String> ans = new ArrayList<>();StringBuilder temp = new StringBuilder();public List<String> letterCombinations(String digits) {if (digits == null || digits.length() == 0) {return ans;}String[] numString = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };backTracking(digits, numString, 0);return ans;}public void backTracking(String digits, String[] numString, int len) {if (len == digits.length()) {ans.add(temp.toString());return;}String str = numString[digits.charAt(len) - '0'];for (int i = 0; i < str.length(); i++) {temp.append(str.charAt(i));backTracking(digits, numString, len + 1);temp.deleteCharAt(temp.length() - 1);}}
}
  1. 組合總和
//未剪枝
class Solution {List<List<Integer>> ans = new ArrayList<>();Deque<Integer> path = new LinkedList<>();public List<List<Integer>> combinationSum(int[] candidates, int target) {bacaktracking(candidates, target, 0, 0);return ans;}public void bacaktracking(int[] candidates, int target, int sum, int startIndex) {if (sum > target) {return;}if (sum == target) {ans.add(new ArrayList<>(path));return;}for (int i = startIndex; i < candidates.length; i++) {sum += candidates[i];path.add(candidates[i]);bacaktracking(candidates, target, sum, i);sum -= candidates[i];path.removeLast();}}
}

在求和問題中,排序之后加剪枝是常見的套路!

//剪枝
class Solution {List<List<Integer>> ans = new ArrayList<>();Deque<Integer> path = new LinkedList<>();public List<List<Integer>> combinationSum(int[] candidates, int target) {Arrays.sort(candidates);bacaktracking(candidates, target, 0, 0);return ans;}public void bacaktracking(int[] candidates, int target, int sum, int startIndex) {if (sum == target) {ans.add(new ArrayList<>(path));return;}for (int i = startIndex; i < candidates.length; i++) {sum += candidates[i];if (sum > target) {break;}path.add(candidates[i]);bacaktracking(candidates, target, sum, i);sum -= candidates[i];path.removeLast();}}
}
  1. 組合總和 II
class Solution {List<List<Integer>> ans = new ArrayList<>();Deque<Integer> path = new LinkedList<>();public List<List<Integer>> combinationSum2(int[] candidates, int target) {Arrays.sort(candidates);backtracking(candidates, target, 0, 0);return ans;}public void backtracking(int[] candidates, int target, int sum, int startIndex) {if (sum == target) {ans.add(new ArrayList<>(path));return;}for (int i = startIndex; i < candidates.length; i++) {if (i > startIndex && candidates[i] == candidates[i - 1]) {continue;}sum += candidates[i];if (sum > target) {break;}path.add(candidates[i]);backtracking(candidates, target, sum, i + 1);sum -= candidates[i];path.removeLast();}}
}
  1. 分割回文串
class Solution {List<List<String>> ans = new ArrayList<>();Deque<String> path = new LinkedList<>();public List<List<String>> partition(String s) {backtracking(s, 0);return ans;}public void backtracking(String s, int startIndex) {if (startIndex >= s.length()) {ans.add(new ArrayList<>(path));return;}for (int i = startIndex; i < s.length(); i++) {if (isPalindrome(s, startIndex, i)) {String str = s.substring(startIndex, i + 1);path.add(str);} else {continue;}backtracking(s, i + 1);path.removeLast();}}public boolean isPalindrome(String s, int start, int end) {for (int i = startIndex, j = end; i < j; i++, j--) {if (s.charAt(i) != s.charAt(j)) {return false;}}return true;}
}
  1. 復原 IP 地址
class Solution {List<String> ans = new ArrayList<>();StringBuilder currentIP = new StringBuilder();public List<String> restoreIpAddresses(String s) {if (s.length() > 12)return ans;backtracking(s, 0, 0);return ans;}private void backtracking(String s, int startIndex, int pointNum) {if (pointNum == 3) {if (isValid(s, startIndex, s.length() - 1)) {currentIP.append(s.substring(startIndex));ans.add(currentIP.toString());}return;}for (int i = startIndex; i < s.length(); i++) {if (isValid(s, startIndex, i)) {int len = currentIP.length();currentIP.append(s.substring(startIndex, i + 1));if (pointNum < 3) {currentIP.append(".");}backtracking(s, i + 1, pointNum + 1);currentIP.setLength(len);} else {break;}}}private Boolean isValid(String s, int start, int end) {if (start > end) {return false;}if (s.charAt(start) == '0' && start != end) { // 0開頭的數字不合法return false;}int num = 0;for (int i = start; i <= end; i++) {if (s.charAt(i) > '9' || s.charAt(i) < '0') { // 遇到非數字字符不合法return false;}num = num * 10 + (s.charAt(i) - '0');if (num > 255) { // 如果大于255了不合法return false;}}return true;}
}
class Solution {List<String> ans = new ArrayList<>();StringBuilder currentIP = new StringBuilder();public List<String> restoreIpAddresses(String s) {if (s.length() > 12)return ans;backtracking(s, 0, 0);return ans;}private void backtracking(String s, int startIndex, int pointNum) {if (pointNum == 3) {if (isValid(s, startIndex, s.length() - 1)) {currentIP.append(s.substring(startIndex));ans.add(currentIP.toString());}return;}for (int i = startIndex; i < s.length(); i++) {if (isValid(s, startIndex, i)) {int len = currentIP.length();currentIP.append(s.substring(startIndex, i + 1));if (pointNum < 3) {currentIP.append(".");}backtracking(s, i + 1, pointNum + 1);currentIP.setLength(len);} else {break;}}}private Boolean isValid(String s, int start, int end) {if (start > end) {return false;}if (s.charAt(start) == '0' && start != end) {return false;}if (Integer.parseInt(s.substring(start, end + 1)) < 0 || Integer.parseInt(s.substring(start, end + 1)) > 255) {return false;}return true;}
}
  1. 子集
class Solution {List<List<Integer>> ans = new ArrayList<>();Deque<Integer> path = new LinkedList<>();public List<List<Integer>> subsets(int[] nums) {backtracking(nums, 0);return ans;}public void backtracking(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]);backtracking(nums, i + 1);path.removeLast();}}}
  1. 子集 II
class Solution {List<List<Integer>> ans = new ArrayList<>();Deque<Integer> path = new LinkedList<>();public List<List<Integer>> subsetsWithDup(int[] nums) {Arrays.sort(nums);backtracking(nums, 0);return ans;}public void backtracking(int[] nums, int startIndex) {ans.add(new ArrayList<>(path));for (int i = startIndex; i < nums.length; i++) {if (i > startIndex && nums[i - 1] == nums[i]) {continue;}path.add(nums[i]);backtracking(nums, i + 1);path.removeLast();}}
}
  1. 非遞減子序列
class Solution {List<List<Integer>> ans = new ArrayList<>();Deque<Integer> path = new LinkedList<>();public List<List<Integer>> findSubsequences(int[] nums) {backtacking(nums, 0);return ans;}public void backtacking(int[] nums, int startIndex) {if (path.size() >= 2) {ans.add(new ArrayList<>(path));}Set<Integer> set = new HashSet<>();for (int i = startIndex; i < nums.length; i++) {if (!path.isEmpty() && path.peekLast() > nums[i] || set.contains(nums[i])) {continue;}set.add(nums[i]);path.add(nums[i]);backtacking(nums, i + 1);path.removeLast();}}
}
  1. 全排列
class Solution {List<List<Integer>> ans = new ArrayList<>();Deque<Integer> path = new LinkedList<>();public List<List<Integer>> permute(int[] nums) {if (nums.length == 0) {return ans;}backtracking(nums, path);return ans;}public void backtracking(int[] nums, Deque<Integer> path) {if (path.size() == nums.length) {ans.add(new ArrayList<>(path));return;}for (int i = 0; i < nums.length; i++) {if (path.contains(nums[i])) {continue;}path.add(nums[i]);backtracking(nums, path);path.removeLast();}}
}

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

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

相關文章

MySql安全加固:可信IP地址訪問控制 設置密碼復雜度

MySql安全加固&#xff1a;可信IP地址訪問控制 & 設置密碼復雜度 1.1 可信IP地址訪問控制1.2 設置密碼復雜度 &#x1f496;The Begin&#x1f496;點點關注&#xff0c;收藏不迷路&#x1f496; 1.1 可信IP地址訪問控制 當您在創建用戶時使用’%作為主機部分&#xff0c;…

【C語言】字符型變量and整型變量的類型轉換

一、將字符型變量轉換為整型變量 char c A; int i (int)c; 二、將整型變量轉換成字符型變量 int i 65; char c (char)i;

Unity 實戰一:這幾年被廣告刷屏的沙雕跑酷游戲

姐就是女王&#xff0c;功夫跑酷&#xff0c;揀槍干架跑酷等 核心不用說了吧&#xff1a; 就是一個人不斷地跑&#xff0c;獲取不同屬性&#xff0c;判斷是否過關 好的&#xff0c;以下是一篇基于Unity 開發簡易版有障礙物的跑酷游戲的教程博客&#xff1a; 在這篇博客中&…

static在c語言中的作用

1、關鍵字static的作用是什么&#xff1f; 這個簡單的問題很少有人能回答完全。在C語言中&#xff0c;關鍵字static有三個明顯的作用&#xff1a; 1). 在函數體&#xff0c;一個被聲明為靜態的變量在這一函數被調用過程中維持其值不變。 2). 在模塊內(但在函數體外)&#xf…

Linux tload 命令教程:實時監控系統負載(附案例詳解和注意事項)

Linux tload 命令介紹 tload 是一個用于監控系統負載的命令行工具。它以圖形化的方式顯示系統的負載情況&#xff0c;幫助你了解 CPU 和內存的使用情況。 Linux tload 命令適用的 Linux 版本 tload 在大多數 Linux 發行版中都可用。如果你在某些特定的 Linux 發行版上找不到…

java數據結構與算法刷題-----LeetCode437. 路徑總和 III(前綴和必須掌握)

java數據結構與算法刷題目錄&#xff08;劍指Offer、LeetCode、ACM&#xff09;-----主目錄-----持續更新(進不去說明我沒寫完)&#xff1a;https://blog.csdn.net/grd_java/article/details/123063846 文章目錄 1. 深度優先2. 前綴和 1. 深度優先 解題思路&#xff1a;時間復…

kibana7.17.7 將數據導出csv文件

配置kibana文件 首先先配置kibana.yaml內容如下&#xff0c;這里假設我的服務器ip地址為192.168.130.128&#xff0c;elasticsearch的ip地址為&#xff1a;192.168.130.129:9200&#xff0c;192.168.130.130:9200&#xff1a; server.host: "192.168.130.128" serv…

每日OJ題_分治歸并③_力扣315. 計算右側小于當前元素的個數

目錄 315. 計算右側小于當前元素的個數 解析代碼 力扣315. 計算右側小于當前元素的個數 315. 計算右側小于當前元素的個數 難度 困難 給你一個整數數組 nums &#xff0c;按要求返回一個新數組 counts 。數組 counts 有該性質&#xff1a; counts[i] 的值是 nums[i] 右側…

MongoDB 未授權訪問

開啟 MongoDB 服務時不添加任何參數時,默認是沒有權限驗證的,而且可以遠程訪問數據庫&#xff0c; 登錄的 用戶可以通過默認端口無需密碼對數據庫進行增、刪、改、查等任意高危操作。 防護 為 MongoDB 添 加 認 證 &#xff1a; 1)MongoDB 啟動時添加–auth參數 2)給 MongoD…

Java 讀寫 ini ( 調用 Windows Api )

市面上讀取 ini 的包都是 讀取整個文件到內存中,再獲取和修改值, 最后自己再調用保存文件, 這種方式在讀取大文件的時候 非常的不友好. windows api 中有現成的高效方法 安裝 jna-platform (里面封裝了各個系統的 api ,直接用就行. 不用再手動寫固定的函數定義) jna-platfor…

JPA常見異常 JPA可能拋出的異常

1、EntityNotFoundException&#xff08;實體不存在異常&#xff09;: 通過 JPA 查找一個不存在的實體。 2、NonUniqueResultException&#xff08;非唯一結果異常&#xff09;&#xff1a; 查詢返回了多個結果&#xff0c;但期望只有一個結果。 3、TransactionRequiredExcep…

AutoSAR(基礎入門篇)13.1-EB Tresos使用初探

目錄 一、新建工程 二、添加和刪除模塊 三、界面 四、代碼生成 1、直接生成代碼

Mac 以SH腳本安裝Arthas

SH腳本安裝Aethas curl -L https://alibaba.github.io/arthas/install.sh | sh安裝腳本說明 示例源文件&#xff1a; #! /bin/bash# temp file of as.sh TEMP_ARTHAS_FILE"./as.sh.$$"# target file of as.sh TARGET_ARTHAS_FILE"./as.sh"# update timeo…

微服務中的Feign:優雅實現遠程調用的秘密武器(一)

本系列文章簡介&#xff1a; 本系列文章將深入探討Feign的特點、原理以及在微服務中的應用場景&#xff0c;幫助讀者更好地理解和使用這個優秀的遠程調用工具。無論您是初學者還是有經驗的開發人員&#xff0c;本文都將為您揭示Feign的秘密&#xff0c;并帶您一起走進微服務的世…

人類與機器的不同交流特點

對人類而言&#xff0c;事實是用來交流的&#xff0c;價值是用來自我交流的。事實是用來交流的&#xff0c;是通過提供準確、可證實的信息來傳遞和共享知識的。事實具有客觀性&#xff0c;不受個人主觀意見的影響。通過分享事實&#xff0c;人們可以更好地理解世界和彼此&#…

Android挖取原圖手指觸點區域RectF(并框線標記)放大到ImageView寬高與矩陣mapRadius,Kotlin

Android挖取原圖手指觸點區域RectF(并框線標記)放大到ImageView寬高與矩陣mapRadius&#xff0c;Kotlin 這里 Android挖取原圖中心區域RectF(并框線標記)放大到ImageView寬高&#xff0c;Kotlin-CSDN博客 實現的是把原圖中心區域的一片小圖挖取出來放大放到下面的ImageView里面…

if語句用法

if語句是單條件分支語句 定義&#xff1a;根據一個條件來控制程序執行流程(如圖3.2)。 語法格式&#xff1a; if&#xff08;表達式&#xff09;{ 若干語句 } ★注意★&#xff1a; ① 表達式的值必須是boolean 型&#xff1b; ② 不能用0代表false&#xff1b;用1代表 true&am…

德人合科技 | —數據泄露可能會對公司造成哪些影響?

數據泄露可能會對公司造成多方面的影響&#xff0c;以下是一些可能的影響&#xff1a; 財務損失&#xff1a;數據泄露可能導致公司遭受財務損失。攻擊者可能會盜取公司的敏感信息&#xff0c;如客戶信息、銀行賬戶信息、商業機密等&#xff0c;并利用這些信息進行欺詐、盜竊等非…

「優選算法刷題」:驗證棧序列

一、題目 給定 pushed 和 popped 兩個序列&#xff0c;每個序列中的 值都不重復&#xff0c;只有當它們可能是在最初空棧上進行的推入 push 和彈出 pop 操作序列的結果時&#xff0c;返回 true&#xff1b;否則&#xff0c;返回 false 。 示例 1&#xff1a; 輸入&#xff1a…

本地maven庫緩存導入私庫

為了加速編譯代碼&#xff0c;想將本地maven緩存導入內網私庫使用。 腳本網上搜的 #!/bin/bash # copy and run this script to the root of the repository directory containing files # this script attempts to exclude uploading itself explicitly so the script name …