tmp如果是传引用的话,需要回溯,也就是把加进去的pop出去。
如果是传参的话,不需要回溯,效率降低一半。复制数组还是很耗时的
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> res;
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<int> tmp;
dfs(root,tmp,targetSum);
return res;
}
void dfs(TreeNode* root, vector<int>& tmp,int sum){
if(root == nullptr) return ;
tmp.emplace_back(root->val);
if(root->val == sum && (root->left == nullptr && root->right == nullptr)){
res.push_back(tmp);
}
dfs(root->left,tmp,sum - root->val);
dfs(root->right,tmp,sum - root->val);
tmp.pop_back(); //传引用需要回溯,在当前节点时tmp数组记录当前状态要把这个节点存进来,现在这个节点的子树已经遍历完了,要把它拿走
}
};