Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Input: digits = “23”
Output: [“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]
Input: digits = “”
Output: []
Input: digits = “2”
Output: [“a”,“b”,“c”]
From: LeetCode
Link: 17. Letter Combinations of a Phone Number
1. Mapping:
2. Calculate Total Combinations:
3. Generate Combinations:
4. Main Function:
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
char ** letterCombinations(char * digits, int* returnSize) {
if (!digits || strlen(digits) == 0) {
*returnSize = 0;
return NULL;
}
char* mapping[] = {
"abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz"
};
int total = 1;
for (int i = 0; i < strlen(digits); i++) {
total *= strlen(mapping[digits[i] - '2']);
}
*returnSize = total;
char** result = (char**) malloc(total * sizeof(char*));
for (int i = 0; i < total; i++) {
result[i] = (char*) malloc((strlen(digits) + 1) * sizeof(char));
int temp = 1;
for (int j = 0; j < strlen(digits); j++) {
int len = strlen(mapping[digits[j] - '2']);
result[i][j] = mapping[digits[j] - '2'][(i / temp) % len];
temp *= len;
}
result[i][strlen(digits)] = '\0';
}
return result;
}