回溯思想
emplace_back()与push_back()的区别
emplace_back 是 C++ 中向 vector、deque 和 list 容器添加元素的成员函数之一。
它与 push_back 类似,都是用于将元素添加到容器的末尾。
但是,emplace_back 在添加元素时使用了完美转发,可以避免不必要的拷贝或移动操作,提高了插入性能。
代码1:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param target int整型
* @return int整型vector<vector<>>
*/
vector<vector<int> >res;
vector<int>path;
void dfs(TreeNode* root, int target){
if(root==NULL){
return ;
}
path.emplace_back(root->val);
target-=root->val;
if(target==0&&root->left==NULL&&root->right==NULL){
res.emplace_back(path);
}
dfs(root->left,target);
dfs(root->right,target);
//将当前元素pop出,回溯到上一层继续遍历
path.pop_back();
}
vector<vector<int> > FindPath(TreeNode* root, int target) {
// write code here
dfs(root, target);
return res;
}
};
代码2:
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param target int整型
* @return int整型vector<vector<>>
*/
vector<vector<int> >res;
vector<int>path;
void dfs(TreeNode* root, int target){
if(root==NULL){
return ;
}
path.push_back(root->val);
target-=root->val;
if(target==0&&root->left==NULL&&root->right==NULL){
res.push_back(path);
}
dfs(root->left,target);
dfs(root->right,target);
//将当前元素pop出,回溯到上一层继续遍历
path.pop_back();
}
vector<vector<int> > FindPath(TreeNode* root, int target) {
// write code here
dfs(root, target);
return res;
}
};
代码1和代码2实现的功能无差别。