784. Letter Case Permutation
Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.
Return a list of all possible strings we could create. Return the output in any order.
Example 1:
Input: s = “a1b2”
Output: [“a1b2”,“a1B2”,“A1b2”,“A1B2”]
Example 2:
Input: s = “3z4”
Output: [“3z4”,“3Z4”]
Constraints:
- <= s.length <= 12
- s consists of lowercase English letters, uppercase English letters, and digits.
From: LeetCode
Link: 784. Letter Case Permutation
Solution:
Ideas:
-
The solution uses backtracking to explore all permutations:
- For each character:
- If it’s a letter, recurse with both lowercase and uppercase.
- If it’s a digit, keep it unchanged and recurse.
- For each character:
-
path is a temporary buffer used to build each permutation.
-
strdup() is used to allocate and copy the finalized permutation string into result.
-
The result array is preallocated with 1 << len slots, which is safe since max s.length = 12.
Code:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
void backtrack(char* s, int index, char** result, int* count, int len, char* path) {
if (index == len) {
path[len] = '\0';
result[*count] = strdup(path);
(*count)++;
return;
}
if (isalpha(s[index])) {
path[index] = tolower(s[index]);
backtrack(s, index + 1, result, count, len, path);
path[index] = toupper(s[index]);
backtrack(s, index + 1, result, count, len, path);
} else {
path[index] = s[index];
backtrack(s, index + 1, result, count, len, path);
}
}
char** letterCasePermutation(char* s, int* returnSize) {
int len = strlen(s);
int maxCombinations = 1 << len; // Upper bound of result size (worst case: all letters)
char** result = (char**)malloc(maxCombinations * sizeof(char*));
char* path = (char*)malloc((len + 1) * sizeof(char));
*returnSize = 0;
backtrack(s, 0, result, returnSize, len, path);
free(path);
return result;
}