标签:style io ar sp for on 数据 ef amp
这道题目DFS用得非常不自信。
(1)递归的用得不够大胆,过分考虑细节了,应该站得高些。
(2)思路厘清之后,要注意状态值的修改,就是状态恢复。深度优先走到底之后,需要返回,此时对应的状态也应该返回。例如之前放到堆栈/vector里的状态数据要弹出来。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void dfs(vector<vector<int>> &res,vector<int> &path,TreeNode *root, int sum){ if(!root) return ; if(!root->left&&!root->right){ if(root->val==sum){ path.push_back(root->val); res.push_back(path); path.pop_back(); } else return; } sum=sum-root->val; path.push_back(root->val); dfs(res,path,root->left,sum); path.pop_back(); path.push_back(root->val); dfs(res,path,root->right,sum); path.pop_back(); } vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int>> res; vector<int> path; dfs(res,path,root,sum); return res; } };
标签:style io ar sp for on 数据 ef amp
原文地址:http://blog.csdn.net/ylzintsinghua/article/details/41825149