LeetCode 784. Letter Case Permutation
给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
示例:
输入: S = “a1b2”
输出: [“a1b2”, “a1B2”, “A1b2”, “A1B2”]
输入: S = “3z4”
输出: [“3z4”, “3Z4”]
输入: S = “12345”
输出: [“12345”]
注意:
S 的长度不超过12。
S 仅由数字和字母组成。
class Solution {
public:
vector<string> ans;
vector<string> letterCasePermutation(string S) {
dfs(S, 0);//传入原字符串 从第0位开始搜索
return ans;
}
void dfs(string &s, int u)
{
if(u == s.size())
{
ans.push_back(s);
return;
}
dfs(s, u + 1);//当前位不变
if(s[u] >= 'A') //当前位是字母 大写字母A 65 小写字母a 97
{
//'A' 65 'a' 97
s[u] ^= 32;//把小写字母变成大写 大写变成小写
dfs(s, u + 1);
}
}
};
LeetCode 77. Combinations
给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
class Solution {
public:
//从小到大选
vector<vector<int>> res;
vector<vector<int>> combine(int n, int k) {
vector<int> path;//当前方案
dfs(path, 1, n, k);
return res;
}
void dfs(vector<int> &path, int start, int n, int k)//起始位置 n k可选个数
{
if(!k)
{
res.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();
}
}
};
LeetCode 257. Binary Tree Paths
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
1
/ \
2 3
\
5
输出: [“1->2->5”, “1->3”]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
/**
* 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> res;
vector<string> binaryTreePaths(TreeNode* root) {
string path; //根节点到当前节点的路径
dfs(root, path);
return res;
}
void dfs(TreeNode* root, string path)
{
if(!root) return;
if(path.size()) path += "->";
path += to_string(root->val);
if(!root->left && !root->right) res.push_back(path);
else
{
dfs(root->left, path);
dfs(root