【DFS】字母大小写全排列

一、题目

. - 力扣(LeetCode). - 备战技术面试?力扣提供海量技术面试资源,帮助你高效提升编程技能,轻松拿下世界 IT 名企 Dream Offer。icon-default.png?t=N7T8https://leetcode.cn/problems/letter-case-permutation/description/

二、题解

枚举每一个位置,如果当前位置是字母就大小写转换后枚举两次

class Solution {
public:
    bool isdigit(char x) {
        return x <= '9' && x >= '0';
    }

    vector<string> res;
    string path, s;
    int n;

    void dfs(int u) {
        if (u == n) {
            res.push_back(path);
            return;
        }

        path += s[u];
        dfs(u + 1);
        path.pop_back();

        if (!isdigit(s[u])) {
            // 如果是大写就转小写 如果是小写就转大写
            path += (s[u] >= 'a' && s[u] <= 'z') ? (char)(s[u] - 'a' + 'A') : (char)(s[u] - 'A' + 'a');
            dfs(u + 1);
            path.pop_back();
        } 
    }

    vector<string> letterCasePermutation(string _s) {
        s = _s;
        n = s.size();
        dfs(0);
        return res;
    }
};
class Solution {
    List<String> res;
    String path;
    String s;
    int n;

    void dfs(int u) {
        if (u == n) {
            res.add(new String(path));
            return;
        }

        path += s.charAt(u);
        dfs(u + 1);
        path = path.substring(0, path.length() - 1);

        if (!(s.charAt(u) <= '9' && s.charAt(u) >= '0')) {
            path += (s.charAt(u) >= 'a' && s.charAt(u) <= 'z') ? (char)(s.charAt(u) - 'a' + 'A') : (char)(s.charAt(u)- 'A' + 'a');
            dfs(u + 1);
            path = path.substring(0, path.length() - 1);
        }
    }

    public List<String> letterCasePermutation(String _s) {
        s = _s;
        n = s.length();
        res = new ArrayList<>();
        path = new String();
        dfs(0);
        return res;
    }
}
  • 12
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值