leetcode (17) - Letter Combinations of a Phone Number

因爲不知道digits的長度到底是多少,不可能寫無數個for循環來遍歷,只能使用遞歸。

void getLetterCom(char** res,char* digits,char* tmp,int index,char map[10][5],int *top){
    int i,digit=digits[index]-'0';
	char* letters;
	
    if(digits[index]==0){
        letters=(char*)malloc(sizeof(char)*index);
        tmp[index]=0;
		strcpy(letters,tmp);
		printf("%s", tmp);
        res[*top]=letters;
		(*top)++;
        return;
    }
    
    for(i=0;map[digit][i];i++){
        tmp[index]=map[digit][i];
      //  printf("%c,", tmp[index]);
        getLetterCom(res,digits,tmp,index+1,map,top);
    
    }
}
char** letterCombinations(char* digits, int* returnSize) {
     // number 0-9
	 char map[10][5]={" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
	 
     char** res,*tmp;
     int num=1,length=0,top=0;
     
     //計算一共有多少種可能,然後malloc
     while(digits[length]){
         if(digits[length]=='0' || digits[length]=='1')continue;
         else if(digits[length]=='7' || digits[length]=='9')num*=4;
         else num*=3;
         length++;
     }
     
     res=(char**)malloc(sizeof(char*)*num);
     if(length==0){
         *returnSize=0;
         return res;
     }
     
     tmp=(char*)malloc(sizeof(char)*length);
     getLetterCom(res,digits,tmp,0,map,&top);
     *returnSize=top;
     return res;
}






發佈了23 篇原創文章 · 獲贊 19 · 訪問量 42萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章