剑指offer第二十四题
题目如下
c++关键字之using
#define DString std::string //! 不建议使用!
typedef std::string TString; //! 使用typedef的方式
using Ustring = std::string; //!使用 using typeName_self = stdtypename;
思路与代码
题目说了路径和为某个值,那么把所有的路径跑下来看是不是等于这个值就可以了啊
这里注意的是要回溯,也就是path.pop_back();
这样才能保证记录下来的是单支路。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
using vvi=vector<vector<int>>;
using vi=vector<int>;
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
vi path;
vvi ret;
if(!root)
return ret;
dfs(root,expectNumber,path,ret);
return ret;
}
void dfs(TreeNode *root,int sum,vi &path,vvi &ret){
path.push_back(root->val);
if(sum==root->val&&!root->left&&!root->right){
ret.push_back(path);
}
if(root->left) dfs(root->left,sum-root->val,path,ret);
if(root->right) dfs(root->right,sum-root->val,path,ret);
path.pop_back();
return ;
}
};