[leetcode] DFS 之 Path Sum 2
来源:互联网 发布:燃烧热数据 编辑:程序博客网 时间:2024/06/07 07:14
题目
分析
这是一题简单的DFS,而且还不是针对于图,只是针对于树的,作为Medium难道可能有算是比较容易的了。但是一开始我还是出现了挺多次问题的,主要是因为一个失误,参数传错了,需要不断地debug,由于这种涉及到指针的问题没有IDE的话debug比较难(不得不说vs的debug很好用,但是如果要开虚拟机再开vs就太麻烦了)。其实这题有个小小的优化,一个就是关于不传vector的副本,而是传其引用,只要记得pop_back就行了。另一个是其实可以把需要找的目标值,还有最终需要返回的目标vector设置成类的私有变量就不需要一直在传递了。
这题的思路很简单,代码量很少,就不多说了。
时间复杂度分析
由于就是简单的二叉树遍历,应该是O(V + E).
代码
/** * 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) { if (root == NULL) return ans; target = sum; vector<int> path; DfsToFindPath(root, 0, path); return ans; } void DfsToFindPath(TreeNode* p, int sum,vector<int>& v) { v.push_back(p->val); sum += p->val; if(p->left != NULL) DfsToFindPath(p->left, sum, v); else if (p->left == NULL && p->right == NULL && sum == target) ans.push_back(v); if (p->right != NULL) DfsToFindPath(p->right, sum, v); v.pop_back(); } // void printPath(vector<int> v,int sum) { // cout << '['; // for (int i = 0; i < v.size(); i++) { // cout << v[i] << ','; // } // cout << ']' << "\t" << sum << endl; // } vector<vector<int> > ans; int target;};
阅读全文
0 0
- [leetcode] DFS 之 Path Sum 2
- Leetcode dfs Path Sum
- Path Sum & Path Sum II | LeetCode DFS
- [leetcode][tree][dfs] Path Sum
- LeetCode 112 Path Sum (DFS)
- leetcode之Path Sum
- LeetCode 之 Path Sum
- LeetCode之Path Sum
- leetcode之 Path Sum
- leetcode 之 path sum
- leetcode之Path Sum
- LeetCode之Path Sum
- leetcode之Path Sum
- leetcode之Path Sum
- leetcode之Path Sum
- LeetCode 之 Path Sum
- [leetcode][tree][dfs] Path Sum II
- [leetcode][dfs] Binary Tree Maximum Path Sum
- MFC入门经典
- 群赛14----2017.9.24
- 计数系统,架构与优化细节
- [BZOJ1509][NOI2003]逃学的小孩(链上乱搞)
- Leetcode 题解系列(二)
- [leetcode] DFS 之 Path Sum 2
- 字符数组和字符指针
- 斐波那契数列的各种求法
- hibernate自动生成实体类和映射文件
- Leetcode [Roman to Integer]
- 文章标题
- 【Java基础】Class.isAssignableFrom与 instanceof 区别
- 学习心得
- JAVA mybatis:初探