Android學習總結之算法篇八(二叉樹和數組)

路徑總和

import java.util.ArrayList;
import java.util.List;// 定義二叉樹節點類
class TreeNode {int val;TreeNode left;TreeNode right;// 構造函數,用于初始化節點值TreeNode(int x) {val = x;}
}public class PathSumProblems {// 路徑總和 I:判斷是否存在從根節點到葉子節點的路徑,使得路徑上所有節點值的和等于給定的目標值public boolean hasPathSumI(TreeNode root, int sum) {// 若根節點為空,不存在滿足條件的路徑if (root == null) {return false;}// 若當前節點為葉子節點,判斷當前節點值是否等于剩余的和if (root.left == null && root.right == null) {return root.val == sum;}// 遞歸在左子樹和右子樹中查找return hasPathSumI(root.left, sum - root.val) || hasPathSumI(root.right, sum - root.val);}// 路徑總和 II:找出所有從根節點到葉子節點的路徑,使得路徑上所有節點值的和等于給定的目標值public List<List<Integer>> pathSumII(TreeNode root, int sum) {List<List<Integer>> result = new ArrayList<>();if (root == null) {return result;}dfsII(root, sum, new ArrayList<>(), result);return result;}// 深度優先搜索輔助方法,用于路徑總和 IIprivate void dfsII(TreeNode node, int remainingSum, List<Integer> currentPath, List<List<Integer>> result) {if (node == null) {return;}// 將當前節點加入路徑currentPath.add(node.val);remainingSum -= node.val;// 若當前節點為葉子節點且剩余和為 0,說明找到了一條滿足條件的路徑if (node.left == null && node.right == null && remainingSum == 0) {result.add(new ArrayList<>(currentPath));}// 遞歸遍歷左子樹和右子樹dfsII(node.left, remainingSum, currentPath, result);dfsII(node.right, remainingSum, currentPath, result);// 回溯,移除當前節點currentPath.remove(currentPath.size() - 1);}// 路徑總和 III:計算二叉樹中路徑和等于給定值的路徑總數,路徑不需要從根節點開始,也不需要在葉子節點結束public int pathSumIII(TreeNode root, int sum) {if (root == null) {return 0;}// 以當前節點為起點的路徑數量int pathsFromRoot = countPathsIII(root, sum);// 左子樹中的路徑數量int pathsInLeft = pathSumIII(root.left, sum);// 右子樹中的路徑數量int pathsInRight = pathSumIII(root.right, sum);return pathsFromRoot + pathsInLeft + pathsInRight;}// 輔助方法,用于計算以當前節點為起點的路徑數量private int countPathsIII(TreeNode node, int remainingSum) {if (node == null) {return 0;}int paths = 0;// 若當前節點值等于剩余和,說明找到了一條路徑if (node.val == remainingSum) {paths++;}// 遞歸在左子樹和右子樹中查找paths += countPathsIII(node.left, remainingSum - node.val);paths += countPathsIII(node.right, remainingSum - node.val);return paths;}public static void main(String[] args) {// 構建一個簡單的二叉樹TreeNode root = new TreeNode(10);root.left = new TreeNode(5);root.right = new TreeNode(-3);root.left.left = new TreeNode(3);root.left.right = new TreeNode(2);root.right.right = new TreeNode(11);root.left.left.left = new TreeNode(3);root.left.left.right = new TreeNode(-2);root.left.right.right = new TreeNode(1);PathSumProblems solution = new PathSumProblems();// 測試路徑總和 Iint targetSumI = 8;boolean resultI = solution.hasPathSumI(root, targetSumI);System.out.println("路徑總和 I:是否存在路徑和為 " + targetSumI + " 的路徑: " + resultI);// 測試路徑總和 IIint targetSumII = 8;List<List<Integer>> resultII = solution.pathSumII(root, targetSumII);System.out.println("路徑總和 II:路徑和為 " + targetSumII + " 的所有路徑: " + resultII);// 測試路徑總和 IIIint targetSumIII = 8;int resultIII = solution.pathSumIII(root, targetSumIII);System.out.println("路徑總和 III:路徑和為 " + targetSumIII + " 的路徑總數: " + resultIII);}
}    

組合總和

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;public class CombinationSumProblems {// 組合總和 I:找出 candidates 中所有可以使數字和為 target 的組合,candidates 中的數字可以無限制重復被選取public List<List<Integer>> combinationSumI(int[] candidates, int target) {List<List<Integer>> result = new ArrayList<>();if (candidates == null || candidates.length == 0) {return result;}// 調用回溯方法backtrackI(candidates, target, 0, new ArrayList<>(), result);return result;}private void backtrackI(int[] candidates, int remaining, int start, List<Integer> current, List<List<Integer>> result) {// 如果剩余值為 0,說明找到了一個有效的組合if (remaining == 0) {result.add(new ArrayList<>(current));return;}// 如果剩余值小于 0,說明當前組合不滿足條件if (remaining < 0) {return;}// 從 start 開始遍歷 candidates 數組for (int i = start; i < candidates.length; i++) {// 將當前數字加入組合current.add(candidates[i]);// 遞歸調用,由于數字可以重復使用,下一次遞歸的 start 仍然是 ibacktrackI(candidates, remaining - candidates[i], i, current, result);// 回溯,移除最后一個數字current.remove(current.size() - 1);}}// 組合總和 II:找出 candidates 中所有可以使數字和為 target 的組合,candidates 中的每個數字在每個組合中只能使用一次public List<List<Integer>> combinationSumII(int[] candidates, int target) {List<List<Integer>> result = new ArrayList<>();if (candidates == null || candidates.length == 0) {return result;}// 對數組進行排序,方便去重Arrays.sort(candidates);// 調用回溯方法backtrackII(candidates, target, 0, new ArrayList<>(), result);return result;}private void backtrackII(int[] candidates, int remaining, int start, List<Integer> current, List<List<Integer>> result) {// 如果剩余值為 0,說明找到了一個有效的組合if (remaining == 0) {result.add(new ArrayList<>(current));return;}// 如果剩余值小于 0,說明當前組合不滿足條件if (remaining < 0) {return;}// 從 start 開始遍歷 candidates 數組for (int i = start; i < candidates.length; i++) {// 跳過重復的數字,避免結果中出現重復組合if (i > start && candidates[i] == candidates[i - 1]) {continue;}// 將當前數字加入組合current.add(candidates[i]);// 遞歸調用,下一次遞歸的 start 為 i + 1,因為每個數字只能使用一次backtrackII(candidates, remaining - candidates[i], i + 1, current, result);// 回溯,移除最后一個數字current.remove(current.size() - 1);}}// 組合總和 III:找出所有相加之和為 n 的 k 個數的組合,組合中只允許含有 1 - 9 的正整數,并且每種組合中不存在重復的數字public List<List<Integer>> combinationSumIII(int k, int n) {List<List<Integer>> result = new ArrayList<>();// 調用回溯方法backtrackIII(k, n, 1, new ArrayList<>(), result);return result;}private void backtrackIII(int k, int remaining, int start, List<Integer> current, List<List<Integer>> result) {// 如果當前組合的長度等于 k 且剩余值為 0,說明找到了一個有效的組合if (current.size() == k && remaining == 0) {result.add(new ArrayList<>(current));return;}// 如果當前組合的長度大于 k 或者剩余值小于 0,說明當前組合不滿足條件if (current.size() > k || remaining < 0) {return;}// 從 start 開始遍歷 1 - 9 的數字for (int i = start; i <= 9; i++) {// 將當前數字加入組合current.add(i);// 遞歸調用,下一次遞歸的 start 為 i + 1,避免重復使用數字backtrackIII(k, remaining - i, i + 1, current, result);// 回溯,移除最后一個數字current.remove(current.size() - 1);}}public static void main(String[] args) {CombinationSumProblems solution = new CombinationSumProblems();// 測試組合總和 Iint[] candidatesI = {2, 3, 6, 7};int targetI = 7;List<List<Integer>> resultI = solution.combinationSumI(candidatesI, targetI);System.out.println("組合總和 I:和為 " + targetI + " 的所有組合: " + resultI);// 測試組合總和 IIint[] candidatesII = {10, 1, 2, 7, 6, 1, 5};int targetII = 8;List<List<Integer>> resultII = solution.combinationSumII(candidatesII, targetII);System.out.println("組合總和 II:和為 " + targetII + " 的所有組合: " + resultII);// 測試組合總和 IIIint k = 3;int n = 9;List<List<Integer>> resultIII = solution.combinationSumIII(k, n);System.out.println("組合總和 III:和為 " + n + " 的 " + k + " 個數的所有組合: " + resultIII);}
}    

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

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

相關文章

Scala和Spark的介紹

Scala 1. Slaca的發展過程 由洛桑聯邦理工學院的馬丁 奧德斯在 2001 年基于 Funnel 的工作開始設計&#xff0c;設計初衷是想集成面向對象編程和函數式編程的各種特性。 Scala 是一種純粹的面向對象的語言&#xff0c;每個值都是對象。 Scala 也是一種函數式語言&#xff0…

配置Hadoop集群環境-使用腳本命令實現集群文件同步

在 Hadoop 集群環境中&#xff0c;確保各節點配置文件一致至關重要。以下是使用 rsync 結合 SSH 實現集群文件同步的腳本方案&#xff0c;支持批量同步文件到所有節點&#xff1a; 1. 前提條件 所有節點已配置 SSH 免密登錄主節點&#xff08;NameNode&#xff09;能通過主機…

Redis能保證數據不丟失嗎之RDB

有了AOF為什么還需要RDB? 上一篇我們介紹了Redis AOF持久化策略。Redis能保證數據不丟失嗎之AOF AOF雖然能實現持久化,但由于AOF恢復數據的時候是一條一條命令重新執行的,但數據量大的時候,Redis數據恢復的時間就會很久,這會導致Redis在重啟的時候,有一大段時間的不可用…

AI浪潮下的藝術突圍戰:對話《名人百科數據庫》執行主編劉鑫煒

當AI生成的畫作在國際賽事中摘冠&#xff0c;當算法推薦主導藝術傳播路徑&#xff0c;技術革命正以前所未有的速度重塑藝術生態。我們獨家專訪深耕藝術推廣領域的劉鑫煒主編&#xff0c;探討當代藝術家在智能時代的生存法則。 圖為《名人百科數據庫》執行主編劉鑫煒 技術重構創…

Python 實現失敗重試功能的幾種方法

更多內容請見: python3案例和總結-專欄介紹和目錄 文章目錄 方法 1:手動 `while` 循環 + 異常捕獲方法 2:使用 `tenacity` 庫(推薦)方法 3:使用 `retrying` 庫(舊版,已停止維護)方法 4:`requests` 自帶重試(適用于 HTTP 請求)方法 5:自定義裝飾器(靈活控制)方法…

2025年滲透測試面試題總結-滲透測試紅隊面試七(題目+回答)

網絡安全領域各種資源&#xff0c;學習文檔&#xff0c;以及工具分享、前沿信息分享、POC、EXP分享。不定期分享各種好玩的項目及好用的工具&#xff0c;歡迎關注。 目錄 滲透測試紅隊面試七 一百八十一、Shiro漏洞類型&#xff0c;721原理&#xff0c;721利用要注意什么&am…

Unity動畫系統使用整理 --- Playable

??Playable API?? 是一個強大的工具&#xff0c;用于更靈活地控制動畫、音頻、腳本等時間軸內容的播放和混合。它提供了比傳統 Animator 更底層、更可控的方式管理時間軸行為&#xff0c;尤其適合復雜動畫邏輯或動態內容組合的場景。 優點&#xff1a; 1.Playables API 支…

基于STM32、HAL庫的BMP390L氣壓傳感器 驅動程序設計

一、簡介: BMP390L 是 Bosch Sensortec 生產的一款高精度氣壓傳感器,專為需要精確測量氣壓和海拔高度的應用場景設計。BMP390L 具有更低的功耗、更高的精度和更快的響應速度。 二、硬件接口: BMP390L 引腳STM32L4XX 引腳說明VDD3.3V電源GNDGND地SCLPB6 (I2C1 SCL)I2C 時鐘線…

Arduino快速入門

Arduino快速入門指南 一、硬件準備 選擇開發板&#xff1a; 推薦使用 Arduino UNO&#xff08;兼容性強&#xff0c;適合初學者&#xff09;&#xff0c;其他常見型號包括NANO&#xff08;體積小&#xff09;、Mega&#xff08;接口更多&#xff09;。準備基礎元件&#xff1a…

破解 Qt QProcess 在 Release 模式下的“卡死”之謎

在使用 Qt 的 QProcess 以調用外部 ffmpeg/ffprobe 進行音視頻處理時&#xff0c;常見的工作流程是&#xff1a; gatherParams&#xff1a;通過 ffprobe 同步獲取媒體文件的參數&#xff08;分辨率、采樣率、聲道數、碼率等&#xff09;。 reencode&#xff1a;逐個文件調用 f…

MySQL 中 UPDATE 結合 SELECT 和 UPDATE CASE WHEN 的示例

概述 以下是 MySQL 中 UPDATE 結合 SELECT 和 UPDATE CASE WHEN 的示例&#xff1a; 一、UPDATE 結合 SELECT&#xff08;跨表更新&#xff09; 場景&#xff1a;根據 orders 表中的訂單總金額&#xff0c;更新 users 表中用戶的 total_spent 字段。 -- 創建測試表 CREATE T…

【MCP】魔搭社區MCP服務(高德地圖、everything文件搜索)

【MCP】魔搭社區MCP服務&#xff08;高德地圖、everything文件搜索&#xff09; 1、上手使用2、環境配置&#xff08;1&#xff09;cherry-studio配置&#xff08;2&#xff09;添加魔搭大模型服務&#xff08;如果已經設置了其他大模型服務&#xff0c;可跳過&#xff09;&…

MapReduce 的工作原理

MapReduce 是一種分布式計算框架&#xff0c;用于處理和生成大規模數據集。它將任務分為兩個主要階段&#xff1a;Map 階段和 Reduce 階段。開發人員可以使用存儲在 HDFS 中的數據&#xff0c;編寫 Hadoop 的 MapReduce 任務&#xff0c;從而實現并行處理1。 MapReduce 的工作…

MCU開啟浮點計算FPU

FPU 測試 1. FPU 簡介2. 協處理器控制寄存器&#xff08;CPACR&#xff09;3. 開啟FPU4. 驗證FPU&#xff08;Julia 分形實驗&#xff09; 1. FPU 簡介 FPU 即浮點運算單元&#xff08;Float Point Unit&#xff09;。浮點運算&#xff0c;對于定點 CPU&#xff08;沒有 FPU 的…

進程相關面試題20道

一、基礎概念與原理 1.進程的定義及其與程序的本質區別是什么&#xff1f; 答案&#xff1a;進程是操作系統分配資源的基本單位&#xff0c;是程序在數據集合上的一次動態執行過程。核心區別&#xff1a;? 動態性&#xff1a;程序是靜態文件&#xff0c;進程是動態執行實例…

React Hooks 精要:從入門到精通的進階之路

Hooks 是 React 16.8 引入的革命性特性,它讓函數組件擁有了類組件的能力。以下是 React Hooks 的詳細使用指南。 一、基礎 Hooks 1. useState - 狀態管理 import { useState } from react;function Counter() {const [count, setCount] = useState(0); // 初始值為0return …

springboot3+vue3融合項目實戰-大事件文章管理系統-更新用戶頭像

大致分為三步 首先在usercontroller里面加入方法 PatchMapping ("/updateAvatar")public Result upadateAvatar(RequestParam URL String avatarUrl){userService.updateAvater(avatarUrl);return Result.success();}url注解能驗證傳入的url是不是合法的&#xff0c…

Mosaic數據增強技術

Mosaic 數據增強技術是一種在計算機視覺領域廣泛應用的數據增強方法。下面是Mosaic 數據增強技術原理的詳細介紹 一、原理 Mosaic 數據增強是將多張圖像&#xff08;通常是 4 張&#xff09;按照一定的規則拼接在一起&#xff0c;形成一張新的圖像。在拼接過程中&#xff0c;會…

Git安裝教程及常用命令

1. 安裝 Git Bash 下載 Git 安裝包 首先&#xff0c;訪問 Git 官方網站 下載適用于 Windows 的 Git 安裝包。 安裝步驟 啟動安裝程序&#xff1a;雙擊下載的 .exe 文件&#xff0c;啟動安裝程序。選擇安裝選項&#xff1a; 安裝路徑&#xff1a;可以選擇默認路徑&#xff0…

學習日志04 java

PTA上的練習復盤 java01 編程題作業感悟&#xff1a; 可以用ai指導自己怎么調試&#xff0c;但是不要把調代碼這過程里面的精華交給ai&#xff0c;就是自己去修正錯誤不能讓ai代勞&#xff01;~~~ 1 scanner.close() Scanner *** new Scanner(System.in); ***.close(); …