第34-3题:LeetCode437. Path Sum III
题目
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1 返回 3。和等于 8 的路径有: 1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
考点
1.map
2.tree
3.dfs
4.递归
5.先序遍历
思路
这道题让我们求二叉树的路径的和等于一个给定值,说明了这条路径不必要从根节点开始,可以是中间的任意一段,而且二叉树的节点值也是有正有负。
那么我们可以用递归来做,相当于先序遍历二叉树。
对于每一个节点都有记录了一条从根节点到当前节点到路径,同时用一个变量curSum记录路径节点总和,然后我们看curSum和sum是否相等,相等的话结果res加1。
不等的话我们来继续查看子路径和有没有满足题意的,做法就是每次去掉一个节点,看路径和是否等于给定值。
注意最后必须留一个节点,不能全去掉了,因为如果全去掉了,路径之和为0,而如果假如给定值刚好为0的话就会有问题。
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
int res = 0;
vector<TreeNode*> out;
helper(root, sum, 0, out, res);
return res;
}
void helper(TreeNode* node, int sum, int curSum, vector<TreeNode*>& out, int& res) {
if (!node) return;
curSum += node->val;
out.push_back(node);
if (curSum == sum) ++res;
int t = curSum;
for (int i = 0; i < out.size() - 1; ++i) {
t -= out[i]->val;
if (t == sum) ++res;
}
helper(node->left, sum, curSum, out, res);
helper(node->right, sum, curSum, out, res);
out.pop_back();
}
};
我们还可以对上面的方法进行一些优化,来去掉一些不必要的计算。
我们可以用哈希表来建立所有的前缀路径之和跟其个数之间的映射,
vector<TreeNode*>& out, int& res ==> unordered_map<int, int>& m
然后看子路径之和有没有等于给定值的。
key的意义是 cur - sum,当 cur - sum == 0时,对应的结果是1个, 即开始就设置 m[0]=1;
记忆搜索,主要思想:记录深度搜索时——从根节点往下的累积和(记为当前和
cur
),并每次将cur
出现次数+1。
- (stl map key如果不存在会自动初始化为0)。
下次使用
m[cur-sum]
如果为一个非0值,则说明从当前节点往上追溯(不一定追溯到根节点)可能存在一个
或多个
符合的路径。
- (比如,假设目标和为8,假设当前节点为
x
,假设有路径4->4和4->4->1->-1->x
则都符合)。
[LeetCode] Path Sum III 二叉树的路径和之三
/**
* 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:
int pathSum(TreeNode* root, int sum) {
unordered_map<int, int> m;//memory
m[0] = 1;//cur - sum = 0, return 1。key的意义是 cur - sum,当 cur - sum == 0时,对应的结果是1个
return dfs(root, sum, 0, m);
}
int dfs(TreeNode* node, int sum, int cur, unordered_map<int, int>& m) {
if (!node) {
return 0;
}
cur += node->val;
int ans = m[cur - sum];
++m[cur];
ans += dfs(node->left, sum, cur, m) + dfs(node->right, sum, cur, m);
--m[cur];
return ans;
}
};
问题
1.
关联容器:unordered_map详细介绍(附可运行代码)
2.std::unordered_map <unordered_map>
template < class Key, // unordered_map::key_type
class T, // unordered_map::mapped_type
class Hash = hash<Key>, // unordered_map::hasher
class Pred = equal_to<Key>, // unordered_map::key_equal
class Alloc = allocator< pair<const Key,T> > // unordered_map::allocator_type
> class unordered_map;Unordered maps are associative containers that store elements formed by the combination of a key value and a mapped value, and which allows for fast retrieval of individual elements based on their keys.
In an unordered_map, the key value is generally used to uniquely identify the element, while the mapped value is an object with the content associated to this key. Types of key and mapped value may differ.
Internally, the elements in the unordered_map are not sorted in any particular order with respect to either their key or mapped values, but organized into buckets depending on their hash values to allow for fast access to individual elements directly by their key values (with a constant average time complexity on average).
unordered_map containers are faster than map containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.
Unordered maps implement the direct access operator (operator[]) which allows for direct access of the mapped value using its key value as argument.
Iterators in the container are at least forward iterators.
Container properties
Associative
Elements in associative containers are referenced by their key and not by their absolute position in the container.
Unordered
Unordered containers organize their elements using hash tables that allow for fast access to elements by their key.
Map
Each element associates a key to a mapped value: Keys are meant to identify the elements whose main content is the mapped value.
Unique keys
No two elements in the container can have equivalent keys.
Allocator-aware
The container uses an allocator object to dynamically handle its storage needs.
Template parameters
Key
Type of the key values. Each element in an unordered_map is uniquely identified by its key value.
Aliased as member type unordered_map::key_type.T
Type of the mapped value. Each element in an unordered_map is used to store some data as its mapped value.
Aliased as member type unordered_map::mapped_type. Note that this is not the same as unordered_map::value_type(see below).Hash
A unary function object type that takes an object of type key type as argument and returns a unique value of type size_t based on it. This can either be a class implementing a function call operator or a pointer to a function (see constructor for an example). This defaults to hash<Key>, which returns a hash value with a probability of collision approaching 1.0/std::numeric_limits<size_t>::max().
The unordered_map object uses the hash values returned by this function to organize its elements internally, speeding up the process of locating individual elements.
Aliased as member type unordered_map::hasher.Pred
A binary predicate that takes two arguments of the key type and returns a bool. The expression pred(a,b), where pred is an object of this type and a and b are key values, shall return true if a is to be considered equivalent to b. This can either be a class implementing a function call operator or a pointer to a function (see constructor for an example). This defaults to equal_to<Key>, which returns the same as applying the equal-to operator (a==b).
The unordered_map object uses this expression to determine whether two element keys are equivalent. No two elements in an unordered_map container can have keys that yield true using this predicate.
Aliased as member type unordered_map::key_equal.Alloc
Type of the allocator object used to define the storage allocation model. By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent.
Aliased as member type unordered_map::allocator_type.In the reference for the unordered_map member functions, these same names (Key, T, Hash, Pred and Alloc) are assumed for the template parameters.
Iterators to elements of unordered_map containers access to both the key and the mapped value. For this, the class defines what is called its value_type, which is a pair class with its first value corresponding to the const version of the key type (template parameter Key) and its second value corresponding to the mapped value (template parameter T):typedef pair<const Key, T> value_type;
Iterators of a unordered_map container point to elements of this value_type. Thus, for an iterator called it that points to an element of a map, its key and mapped value can be accessed respectively with:
unordered_map<Key,T>::iterator it;
(*it).first; // the key value (of type Key)
(*it).second; // the mapped value (of type T)
(*it); // the "element value" (of type pair<const Key,T>)
Naturally, any other direct access operator, such as -> or [] can be used, for example:
it->first; // same as (*it).first (the key value)
it->second; // same as (*it).second (the mapped value)
3.function template <string> std::stoi
template<class ForwardIterator, class T>
void iota(ForwardIterator first, ForwardIterator last, T value)
{
while(first != last) {
*first++ = value;
++value;
}
}#include <algorithm>
#include <iostream>
#include <list>
#include <numeric>
#include <random>
#include <vector> int main()
{
std::list<int> l(10);
std::iota(l.begin(), l.end(), -4); std::vector<std::list<int>::iterator> v(l.size());
std::iota(v.begin(), v.end(), l.begin()); std::shuffle(v.begin(), v.end(), std::mt19937{std::random_device{}()}); std::cout << "Contents of the list: ";
for(auto n: l) std::cout << n << ' ';
std::cout << '\n'; std::cout << "Contents of the list, shuffled: ";
for(auto i: v) std::cout << *i << ' ';
std::cout << '\n';
}可能的输出
Contents of the list: -4 -3 -2 -1 0 1 2 3 4 5
Contents of the list, shuffled: 0 -1 3 4 -4 1 -2 -3 2 54.class <sstream> std::stringstream
5.function template <algorithm> std::find_if
template<class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
while (first!=last) {
if (pred(*first)) return first;
++first;
}
return last;
}// find_if example
#include <iostream> // std::cout
#include <algorithm> // std::find_if
#include <vector> // std::vector bool IsOdd (int i) {
return ((i%2)==1);
} int main () {
std::vector<int> myvector; myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55); std::vector<int>::iterator it = std::find_if (myvector.begin(), myvector.end(), IsOdd);
std::cout << "The first odd value is " << *it << '\n'; return 0;
}The first odd value is 25
6.std::basic_string::substr
basic_string substr( size_type pos = 0,
size_type count = npos ) const;
7.C++ 具名要求: Predicate
谓词 (Predicate) 要求描述可调用 (Callable) 对象返回可作为 bool 测试的值。
谓词 (Predicate) 常用于接收输入数据(单独的对象/容器)和谓词的算法,然后在进一步行动时得到调用。 C++ 标准库中的一些谓词使用示例是:
- std::all_of 、 std::any_of 、 std::none_of 接收元素范围和谓词为输入。在每个单独的输入元素上调用谓词,并且若谓词分别对全部/任一/无元素返回 true 则返回 true 。
- std::find_if 接受元素序列和谓词。返回序列中的首个谓词对其返回的 true 的元素。
上面给出的算法设施描述是简陋的,并且有意地简要解释谓词 (Predicate) 。对于详细信息可查阅单独的页面。
换言之,若算法接收谓词 (Predicate)
pred
和迭代器first
,则它应该能经由类似 if(pred(*first)) {...} 的构造,测试迭代器first
所指向的类型。函数对象
pred
不应当通过解引用的迭代器应用任何非 const 函数。此函数对象可以是指向函数的指针或拥有适合的函数调用运算符的类型的对象。
8.如何调用另一个cpp文件中的子函数
在A中声明一个c函数头就行,链接程序会自动找到B.obj中的c函数的
A.cpp
int c();声明
main()
{
} B.cpp
int c()定义
{
}
第34-3题:LeetCode437. Path Sum III的更多相关文章
- 437. Path Sum III
原题: 437. Path Sum III 解题: 思路1就是:以根节点开始遍历找到适合路径,以根节点的左孩子节点开始遍历,然后以根节点的右孩子节点开始遍历,不断循环,也就是以每个节点为起始遍历点 代 ...
- 47. leetcode 437. Path Sum III
437. Path Sum III You are given a binary tree in which each node contains an integer value. Find the ...
- 【leetcode】437. Path Sum III
problem 437. Path Sum III 参考 1. Leetcode_437. Path Sum III; 完
- leetcode 112. Path Sum 、 113. Path Sum II 、437. Path Sum III
112. Path Sum 自己的一个错误写法: class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if(root ...
- LeetCode_437. Path Sum III
437. Path Sum III Easy You are given a binary tree in which each node contains an integer value. Fin ...
- LeetCode算法题-Path Sum III(Java实现)
这是悦乐书的第227次更新 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第94题(顺位题号是437).您将获得一个二叉树,其中每个节点都包含一个整数值.找到与给定值相加的路径数 ...
- [LeetCode] Path Sum III 二叉树的路径和之三
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- LeetCode 437. Path Sum III (路径之和之三)
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- [LeetCode] 437. Path Sum III 路径和 III
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
随机推荐
- P2P原理和NAT打洞
1. P2P协议--点对点通信 1.1 常用的P2P协议 1.1.1 电驴(eMule) 一个电驴网络由服务器端和客户端两部分组成. 服务器端是客户端连接的.为了搜索和查找可以下载用户的桥梁.客户通过 ...
- php和c++socket通讯(基于字节流,二进制)
研究了一下PHP和C++socket通讯,用C++作为服务器端,php作为客户端进行. socket通讯是基于协议的,因此,只要双方协议一致就行. 关于协议的选择:我看过网上大部分协议都是在应用层的协 ...
- 判断表单中是否含有disabled属性
我想判断input里面是否有disabled.或者选中未选中的selected checked 属性时,需要用 prop() 方法,返回的结果是 true 或 false . attr()这个方 ...
- http method and status code
http method HEAD: 只返回相应的header POST: 一般用于提交表单 PUT: 向Web服务器上传文件 GET: 查 DELET: 删除 status code 1xx与2xx: ...
- POJ 3164——Command Network——————【最小树形图、固定根】
Command Network Time Limit: 1000MS Memory Limit: 131072K Total Submissions: 15080 Accepted: 4331 ...
- Slickflow.NET 开源工作流引擎基础介绍-.NET Core2.0 版本实现介绍 (转)
前言:.NET Core 是.NET Framework的新一代版本,是微软开发的第一个跨平台 (Windows.Mac OSX.Linux) 的应用程序开发框架(Application Framew ...
- HDU5972Regular Number(ShiftAnd算法 bitset)
题意 题目链接 第一行的\(n\)表示模式串长度为\(n\) 接下来\(n\)行,每行开头有一个整数\(num\)表示匹配串中该位置的字符可以在\(num\)个桅子花出现,接下来输入这\(num\)个 ...
- 关于Android Studio中的一个小问题——R文件引用Id失败
错误情况: 今天使用AS建立了一个新的EmptyProject,结果出现错误 setContentView(R.layout.activity_main); R文件的引用Id失败.真的是莫名奇妙... ...
- u-boot分析(二)----工作流程分析
u-boot分析(二) 由于这两天家里有点事,所以耽误了点时间,没有按时更新,今天我首先要跟大家说说我对于u-boot分析的整体的思路,然后呢我以后的博客会按照这个内容更新,希望大家关注. 言归正传, ...
- DOM对象和js对象以及jQuery对象的区别
DOM对象和js对象以及jQuery对象的区别 DOM对象和js对象以及jQuery对象的区别 一.DOM对象 文档对象模型简称DOM,是W3C组织推荐的处理可扩展置标语言的标准编程接口. DOM实际 ...