日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode面试题 04.12. 求和路径(dfs)

發布時間:2023/11/29 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode面试题 04.12. 求和路径(dfs) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一棵二叉樹,其中每個節點都含有一個整數數值(該值或正或負)。設計一個算法,打印節點數值總和等于某個給定值的所有路徑的數量。注意,路徑不一定非得從二叉樹的根節點或葉節點開始或結束,但是其方向必須向下(只能從父節點指向子節點方向)。示例: 給定如下二叉樹,以及目標和 sum = 225/ \4 8/ / \11 13 4/ \ / \7 2 5 1 返回:3 解釋:和為 22 的路徑有:[5,4,11,2], [5,8,4,5], [4,11,7]

代碼

/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ class Solution {int tar, cnt = 0;public int pathSum(TreeNode root, int sum) {tar = sum;Sum(root, 0, new LinkedList<>());return cnt;}public void Sum(TreeNode root, int sum, LinkedList<Integer> res) {//dfsif (root == null) return;res.add(root.val);cnt += um(res);Sum(root.left, sum + root.val, res);Sum(root.right, sum + root.val, res);res.removeLast();}public int um(LinkedList<Integer> res) {//找當前數組符合的連續子數組int temp = 0, r = 0;for (int i = res.size() - 1; i >= 0; i--) {r += res.get(i);if (r == tar) temp++;}return temp;} }

遞歸+前綴和+回溯代碼

/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ class Solution {int tar;public int pathSum(TreeNode root, int sum) {tar = sum;HashMap<Integer,Integer> map=new HashMap<>();map.put(0,1);//節點本身也算路徑return helper(root, 0,map);}public int helper(TreeNode root, int sum, HashMap<Integer,Integer> map) {if (root == null) return 0;int cnt=0;int res=sum+root.val;cnt +=map.getOrDefault(res-tar,0);//符合的前綴和出現的次數就是路徑的數量map.put(res,map.getOrDefault(res,0)+1);if(root.left!=null) cnt+=helper(root.left, res, map);if(root.right!=null) cnt+=helper(root.right, res, map);map.put(res,map.get(res)-1);//回溯return cnt;} }

總結

以上是生活随笔為你收集整理的leetcode面试题 04.12. 求和路径(dfs)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。