# 784. Letter Case Permutation

Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.  Return a list of all possible strings we could create.

``````Examples:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]

Input: S = "3z4"
Output: ["3z4", "3Z4"]

Input: S = "12345"
Output: ["12345"]
``````

Note:

• `S` will be a string with length at most `12`.
• `S` will consist only of letters or digits.

``````class Solution {
public:
vector<string> letterCasePermutation(string S) {
vector<string> res{""};
for (char c : S) {
int len = res.size();
if (c >= '0' && c <= '9') {
for (string &str : res) str.push_back(c);
} else {
for (int i = 0; i < len; ++i) {
res.push_back(res[i]);
res[i].push_back(tolower(c));
res[len + i].push_back(toupper(c));
}
}
}
return res;
}
};
``````

``````class Solution {
public:
vector<string> letterCasePermutation(string S) {
vector<string> res{""};
for (char c : S) {
int len = res.size();
if (c >= '0' && c <= '9') {
for (string &str : res) str.push_back(c);
} else {
for (int i = 0; i < len; ++i) {
res.push_back(res[i]);
res[i].push_back(c);
res[len + i].push_back(c ^ 32);
}
}
}
return res;
}
};
``````

``````class Solution {
public:
vector<string> letterCasePermutation(string S) {
vector<string> res;
helper(S, 0, res);
return res;
}
void helper(string& s, int pos, vector<string>& res) {
if (pos == s.size()) {
res.push_back(s);
return;
}
helper(s, pos + 1, res);
if (s[pos] > '9') {
s[pos] ^= 32;
helper(s, pos + 1, res);
}
}
};
``````

``````000 -> ABC
001 -> ABc
010 -> AbC
011 -> Abc
100 -> aBC
101 -> aBc
110 -> abC
111 -> abc
``````

``````class Solution {
public:
vector<string> letterCasePermutation(string S) {
vector<string> res;
int cnt = 0;
for (char c : S) {
if (c > '9') ++cnt;
}
for (int i = 0; i < (1 << cnt); ++i) {
int j = 0;
string word = "";
for (char c : S) {
if (c > '9') {
if (((i >> j++) & 1) == 1) {
word.push_back(tolower(c));
} else {
word.push_back(toupper(c));
}
} else {
word.push_back(c);
}
}
res.push_back(word);
}
return res;
}
};
``````

Subsets

https://leetcode.com/problems/letter-case-permutation/solution/

https://leetcode.com/problems/letter-case-permutation/discuss/115515/C++-backtrack-solution-w-trick

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation