leetcode | Path Sum II
2015-07-03 18:48
323 查看
Path Sum II : https://leetcode.com/problems/path-sum-ii/
这里写图片描述
解析:
和上一题的区别就是,要记录所有能满足条件的路径。
要保存路径 : 保存当前的结果,并且每次递归后都要恢复递归前的结果;每当满足了保存条件(递归到叶子节点时),判断是否需要当前结果(path)保存下来。
叶节点时 sum == 0, 保存当前结果,然后逐步恢复递归前结果
叶节点时 sum != 0,不保存当前结果,然后逐步恢复递归前结果
这里写图片描述
解析:
和上一题的区别就是,要记录所有能满足条件的路径。
要保存路径 : 保存当前的结果,并且每次递归后都要恢复递归前的结果;每当满足了保存条件(递归到叶子节点时),判断是否需要当前结果(path)保存下来。
叶节点时 sum == 0, 保存当前结果,然后逐步恢复递归前结果
叶节点时 sum != 0,不保存当前结果,然后逐步恢复递归前结果
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> result; if (root == NULL) return result; vector<int> path; // 存储一条路径 path.push_back(root->val); DFS(root, sum-(root->val), path, result); return result; } void DFS(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &result) { if (root == NULL) return; if (root->left == NULL && root->right == NULL && 0 == sum) { result.push_back(path); // 整条路径已跑完; return; } // 左子树非空,遍历左子树 if (root->left != NULL) { path.push_back(root->left->val); // 先推进去,记忆该节点 DFS(root->left, sum-(root->left->val), path, result); path.pop_back(); // 用完后需要清除最后一个,下一个路径(它的兄弟节点)还要用 } // 右子树非空,遍历右子树 if (root->right != NULL) { path.push_back(root->right->val); DFS(root->right, sum-(root->right->val), path, result); path.pop_back();// 恢复递归前结果 } } };
相关文章推荐
- ngx映射到lua模块函数变量一览
- NYOJ 977 最大的最小公倍数
- 什么是LSP???如何看待LSP???
- 关于SIGPIPE导致的程序退出
- awk 匹配不是 pattern 的内容
- ActionBar属性和效果修改
- Nginx 与 Lua
- 九度1483 求最大最小数
- Python笔记:MySQLdb模块常用操作
- 线程锁
- 使用Builder模式造车
- JAVA并发
- NYOJ 236 心急的c小加
- 国产手机在mac os中无法被adb识别的解决方法(转)
- sqlserver 除法运算结果为小数时显示0
- 大二下学期总结
- CHANGE MASTER TO语法
- Stackoverflow/dapper的Dapper-Extensions用法(二)
- 【iOS开发系列】更换头像(相机、相册)
- Unix/Linux中的read和write函数