DFS专题

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值