题目:Letter Combinations of a Phone Number
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
递归法,代码.
void getStr(char* digits,int index,char map[10][5],char** ret,char* tmp,int* sub);
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
char** letterCombinations(char* digits, int* returnSize) {
int i=0;
int num=1;
char** ret;
int sub=0;
int length=strlen(digits);
if(length==0) return "";
char map[10][5]={" "," ","abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
char* tmp=(char *)malloc(sizeof(char)*length);//暂时保存的字符串
while(i<length)
{
int t=digits[i++]-'0';
if(t==0 || t==1) return "";
else if(t==7 || t==9) num*=4;
else num*=3;
}
ret=(char **)malloc(sizeof(char *)*num); //开辟空间
getStr(digits,0,map,ret,tmp,&sub);
*returnSize=sub;
return ret;
}
void getStr(char* digits,int index,char map[10][5],char** ret,char* tmp,int* sub)
{
int i=0;
int len=strlen(digits);
if(index== len)
{
ret[(*sub)]=(char*)malloc(sizeof(char)*(len+1)); //保存数据
for(i=0;i<len;i++)
{
printf("The character is %c ",tmp[i]);
ret[*sub][i]=tmp[i];
}
ret[*sub][i]='\0';
(*sub)++;
return;
}
int number=digits[index]-'0';
//printf("The number is %d %d\n",number,digits[0]);
for(i=0; i<strlen(map[number]);i++)
{
tmp[index]=map[number][i];
getStr(digits,index+1,map,ret,tmp,sub);
}
}