[回溯法][树]leetcode113:路径总和 Ⅱ (medium)

编程入门 行业动态 更新时间:2024-10-26 23:41:21

[回溯法][树]leetcode113:路径<a href=https://www.elefans.com/category/jswz/34/1771016.html style=总和 Ⅱ (medium)"/>

[回溯法][树]leetcode113:路径总和 Ⅱ (medium)

题目:


题解:

  • 回溯法
  • 对于树形结构采用dfs的策略寻找所有可行解,就是运用的回溯法。在到达叶子节点且节点值等于sum的剩余值表示找到一个可行解,若不等于表示没有找到可行解,则我们需要回溯到上一步。细节问题,可见代码。

代码如下:

class Solution {
public:vector<vector<int>> res;vector<int> path;vector<vector<int>> pathSum(TreeNode* root, int t) {dfs(root,t);return res;}void dfs(TreeNode* root,int t){if(!root)return;t-=root->val,path.push_back(root->val);if(!root->right and !root->left and !t)res.push_back(path);dfs(root->left,t),dfs(root->right,t);// 等到回溯到分支时就删除之前添加的节点t+=root->val,path.pop_back();}
};

更多推荐

[回溯法][树]leetcode113:路径总和 Ⅱ (medium)

本文发布于:2023-07-28 18:53:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1279946.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   路径   medium

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!