知序
返回
保存草稿
发布
H1
H2
H3
1
2
3
Excalidraw 图
AI 写作
AI 优化
目录
输入内容后显示目录
Markdown
# 76 - 路径总和II ## 题目(LeetCode 113) 找出所有从根到叶子路径总和等于目标值的路径。 ## 解法:DFS 回溯 ```java class Solution { public List<List<Integer>> pathSum(TreeNode root, int targetSum) { List<List<Integer>> res = new ArrayList<>(); dfs(root, targetSum, new ArrayList<>(), res); return res; } private void dfs(TreeNode node, int remain, List<Integer> path, List<List<Integer>> res) { if (node == null) return; path.add(node.val); if (node.left == null && node.right == null && remain == node.val) res.add(new ArrayList<>(path)); dfs(node.left, remain - node.val, path, res); dfs(node.right, remain - node.val, path, res); path.remove(path.size() - 1); } } ``` ## 复杂度 - 时间 O(n²),空间 O(n) ## 一句话总结 DFS 遍历所有根到叶子路径,回溯记录满足条件的路径。 ## 说明 路径总和 II 需要找出所有满足条件的路径,DFS 回溯是唯一合适的方法。时间复杂度 O(n²) 是因为最坏情况下需要复制 O(n) 长度的路径 O(n) 次。当前解法已是最优。
预览
发布文章
添加摘要让读者更快了解文章内容
取消
确认发布
AI 写作助手
输入一个主题,AI 将为你生成一篇 Markdown 博客文章
AI 正在写作中...
取消
开始生成
AI 优化助手
描述你的修改需求,AI 将在原文基础上进行补充或微调
AI 正在优化中...
取消
开始优化
画布
从已有图里选
✕
图名
保存后生成 /images/excalidraw/<图名>.svg(只能用字母、数字、短横线、下划线、点)
取消
保存并插入