437. Path Sum III--dfs + hash + 連續序列的和等於給定的數num
阿新 • • 發佈:2018-12-31
You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11這題可以分成兩部分來考慮:1)樹的遍歷,很明顯用dfs;2)另外就是:陣列中,連續序列的和等於給定的數num的個數。後面的問題用什麼方法呢 ?
可以用最簡單的方法,計算陣列中兩兩之間的所有數的和,看看是否等於num,但時間複雜度為O(n^2);
可以用雜湊表的方法,用雜湊表記錄下前N項的值出現的次數,即hash[ sum[N] ]++;程式碼:
迴歸到原題的話,解就是dfs和連續序列的和等於給定的數num的個數的結合了。discuss中的程式碼如下,它的時間複雜度為O(n)。int count(vector<int> vec, int num){ unordered_map<int, int> m; int res = 0, prev = 0; for(int i = 0; i < vec.size(); ++i){ prev += vec[i]; m[prev]++; res += (prev==num) + m[prev-num]; } return res; }
並且有個細節,在dfs中,若有陣列(不是常數的記憶體)等作為引數傳遞時,最好用引用&。這樣就避免了很多次的資料複製,節省大量的時間和空間。如下面的
unordered_map<int, int>& store
注意這裡還得在子函式呼叫的後面加上一句
store[root->val]--;
為的是"復原現場"。
class Solution {
public:
int help(TreeNode* root, int sum, unordered_map<int, int>& store, int pre) {
if (!root) return 0;
root->val += pre;
int res = (root->val == sum) + (store.count(root->val - sum) ? store[root->val - sum] : 0);
store[root->val]++;
res += help(root->left, sum, store, root->val) + help(root->right, sum, store, root->val); <pre name="code" class="cpp" style="font-size: 14px; line-height: 30px;"><span style="white-space:pre"> </span>store[root->val]--;
return res; } int pathSum(TreeNode* root, int sum) { unordered_map<int, int> store; return help(root, sum, store, 0); }};