1. 二叉樹路徑總和
LeetCode 113 給定一個二叉樹和一個目標和肚豺,找到所有從根節(jié)點到葉子節(jié)點路徑總和等于給定目標和的路徑筷狼。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> ans;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int> path;
dfs(path,root,sum);
return ans;
}
void dfs(vector<int>& path,TreeNode* root, int sum)
{
if(!root) return;
path.push_back(root->val);
if(!root->left && !root->right)
{
int sum2 = accumulate(path.begin(),path.end(),0);
if(sum2 == sum)
{
ans.push_back(path);
return;
}
}
else
{
dfs(path, root->left,sum);
if(root->left)
path.pop_back();
dfs(path, root->right,sum);
if(root->right)
path.pop_back();
}
}
};
如若不使用引用柬批,則不需要恢復(fù)現(xiàn)場
2. 字母大小寫全排列
Leetcode 784 給定一個字符串S实幕,通過將字符串S中的每個字母轉(zhuǎn)變大小寫卸奉,我們可以獲得一個新的字符串空厌。返回所有可能得到的字符串集合庐船。
class Solution {
public:
vector<string> ans;
vector<string> letterCasePermutation(string S) {
dfs(S,0);
return ans;
}
void dfs(string s, int i)
{
if(i == s.size())
{
ans.push_back(s);
return;
}
dfs(s,i+1);
if(s[i] >= 'A')
{
s[i] ^= 32;
dfs(s,i+1);
}
}
};
3. 組合
Leetcode 77 從n個數(shù)中選k個
class Solution {
public:
vector<vector<int>> ans;
vector<vector<int>> combine(int n, int k) {
vector<int> path;
dfs(path, 1, n, k);
return ans;
}
void dfs(vector<int> &path, int start, int n, int k)
{
if(!k)
{
ans.push_back(path);
return;
}
for(int i = start; i <= n; i++)
{
path.push_back(i);
dfs(path, i+1, n, k-1);
path.pop_back();
}
}
};
4. 二叉樹所有路徑
Leetcode 257 給定一個二叉樹,返回所有從根節(jié)點到葉子節(jié)點的路徑嘲更。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<string> ans;
vector<string> binaryTreePaths(TreeNode* root) {
string path;
dfs(root, path);
return ans;
}
void dfs(TreeNode * root, string path)
{
if(!root) return;
if(path.size()) path += "->";
path += to_string(root->val);
if(!root->left && !root->right) ans.push_back(path);
else
{
dfs(root->left,path);
dfs(root->right,path);
}
}
};