关于《剑指offer》某算法题的疑惑?
今天在刷《剑指offer》中“二叉树中和为某一值的路径”题目时,没有什么思路,参考了相关大神的代码和思路之后,自己写了一下,但是遇到了一个实现细节的问题。先贴代码:
class Solution { public: vector<vector<int> > res;//存放满足条件的所有路径 vector<int> subRes; //存放某一条合格的路径 vector<vector<int> > FindPath(TreeNode* root,int expectNumber) { //vector<vector<int> > res; //vector<int> subRes; if(root == NULL) return res; bool isLeaf = (root->left == NULL) && (root->right == NULL);//判断结点是否为叶子结点 subRes.push_back(root->val); if((expectNumber - root->val) == 0 && isLeaf){ res.push_back(subRes); } if(root->left) FindPath(root->left, expectNumber - root->val); if(root->right) FindPath(root->right, expectNumber - root->val); if(subRes.size()) subRes.pop_back(); return res; } };
问题就处在变量的声明,业绩代码中注释的两句,开始的时候将两个变量res 和 subRes声明在函数体内,但是无法通过测试用例,也就是有错误,但是,将两个变来那个放在函数体外面的时候,就一切正常了。 请问这是怎么回事呢? public的变量,与在函数体内的变量的区别是全局变量与局部变量的区别是吗?但是为什么要是将两个变量声明为全局变量呢?