【LeetCode-中等】784. 字母大小写全排列 - 递归

784. 字母大小写全排列

解法:递归
从左往右依次遍历字符,过程中保持 ans 为已遍历过字符的字母大小全排列。
例如,当 S = “abc” 时,考虑字母 “a”, “b”, “c”,初始令 ans = [""],依次更新 ans = [“a”, “A”], ans = [“ab”, “Ab”, “aB”, “AB”], ans = [“abc”, “Abc”, “aBc”, “ABc”, “abC”, “AbC”, “aBC”, “ABC”]。
如果下一个字符 c 是字母,将当前已遍历过的字符串全排列“复制两份”,在第一份的每个字符串末尾添加 toupper( c ),在第二份的每个字符串末尾添加 tolower( c )。
isalpha():判断一个字符是否是字母
toupper():将小写字母转换为大写字母
tolower():将大写字母转换为小写字母
注意:toupper() 和 tolower() 的返回值为 int 。

class Solution {
public:
    vector<string> ans;
    vector<string> letterCasePermutation(string s) {
        dfs("",0,s);
        return ans;
    }
    void dfs(string temp, int cur,string s){
        if(cur==s.size()){
            ans.push_back(temp);
            return;
        }
        if(isalpha(s[cur])){
            char up=toupper(s[cur]);
            char down=tolower(s[cur]);
            dfs(temp+down,cur+1,s);
            dfs(temp+up,cur+1,s);
        }else{
            dfs(temp+s[cur],cur+1,s);
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值