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);
}
}
};