给出手机上的字符按键顺序,求所有可能的按出的字符串。简单dfs搜索,0ms
const char* map[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
void dfs(char* digits, char* pre, char** res, int* returnSize) {
if (!digits[0]) {
res[*returnSize] = malloc(strlen(pre) + 1);
strcpy(res[*returnSize], pre);
(*returnSize)++;
return;
}
int i;
char* mapstr = map[digits[0] - '2'];
for (i = 0 ; i < strlen(mapstr) ; i++) {
int oldpre = strlen(pre);
pre[oldpre] = mapstr[i];
pre[oldpre+1] = 0;
dfs(digits+1, pre, res, returnSize);
pre[oldpre] = 0;
}
}
char** letterCombinations(char* digits, int* returnSize) {
int i, j;
*returnSize = 0;
if (digits[0] == 0) return NULL;
for (i = 0 ; i < strlen(digits) ; i++)
if (!strchr("23456789", digits[i]))
return NULL;
char** res = malloc(sizeof(char*) * (27 * 27 * 16));
char* pre = malloc(strlen(digits) + 1);
pre[0] = 0;
dfs(digits, pre, res, returnSize);
free(pre);
return res;
}