#17 Letter Combinations of a Phone Number

題目鏈接:https://leetcode.com/problems/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.

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
void SubCombination(char* digits, char map[][5], char* output, char** ret, int* returnSize, int k) {    //k表示遞歸到當前字母的下標
    int i = 0;
    if(digits[k] == '\0') {     //基準情況;遞歸到字符串結束處,將當前輸
        output[k] = '\0';
        if(k)
            strcpy(ret[(*returnSize)++], output);       //複製字符串到輸出數組
        return;
    }
    while(map[digits[k] -  '0'][i]) { //當前數字對應的每一個字母進行遞歸
        output[k] = map[digits[k] - '0'][i];
        SubCombination(digits, map, output, ret, returnSize, k + 1);
        ++i;
    }
}
char** letterCombinations(char* digits, int* returnSize) {
    *returnSize = 0;
    char map[10][5] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
    char output[20] = {};       //輸出字符串
    char **ret = (char **)malloc(sizeof(char *) * 1000);
    for(int i = 0; i < 1000; ++i)
        ret[i] = (char *)malloc(sizeof(char) * 20);
    SubCombination(digits, map, output, ret, returnSize, 0);    //從第一個字母開始遞歸保存每一個數字對應字母,到結尾處保存對應字符串
    return ret;
}


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