同步发于 JuzerTech 网站,里面有我软、硬件学习的纪录与科技产品开箱,欢迎进去观看。
传统手机透过数字键来打字,一个数字键通常代表了多个英文字母,例如2 代表a , b , c ,3 代表d , e , f 等,连续按多个键能产生英文字母的组合,此题为给定数字,输出所有可能的英文字母组合。
题目与范例如下
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 digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = ""
Output: []
Example 3:
Input: digits = "2"
Output: ["a","b","c"]
Constraints:
0 <= digits.length <= 4
digits[i] is a digit in the range ['2', '9'].
Accepted
861,326
Submissions
1,706,491
解题方式为透过递归的方式,透过 for 回圈把每个数字可能的英文字母遍历出来,分别递归。填完字母后,补上结束字元 ' \0 ' 转存回要回传的空间内。
下方为我的代码
char map[10][5]={{},{},{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}};
int reindex = 0;
char **re;
char *DPtr;
void Rnum( int index, char *tempstr){ // index use for input string index and tempstr index
if(DPtr[index] == '\0'){
tempstr[index] = '\0';
re[reindex] = (char*)malloc(sizeof(char)*(strlen(DPtr)+1));
strcpy(re[reindex],tempstr);
reindex++;
}
else{
for(int i = 0;i<strlen(map[DPtr[index]-'0']);i++){
tempstr[index] = map[DPtr[index]-'0'][i];
Rnum(index+1,tempstr);
}
}
}
char ** letterCombinations(char * digits, int* returnSize){
DPtr = digits;
reindex = 0;
if(strlen(digits) != 0){
(*returnSize) = 1;
for(int i = 0 ; i < strlen(digits) ; i++ ){
(*returnSize) *= strlen(map[digits[i]-'0']);
}
}
else{
(*returnSize) = 0;
}
re = (char**)malloc(sizeof(char*)*(*returnSize));
char tempstr[5] = {0};
if((*returnSize)>0)
Rnum( 0, tempstr);
return re;
}
下方为时间与空间之消耗
Runtime: 0 ms, faster than 100 % of C online submissions for Letter Combinations of a Phone Number.
Memory Usage: 5.7 MB, less than 98.79 % of C online submissions for Letter Combinations of a Phone Number.