17. Letter Combinations of a Phone Number (backtracking)

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"].

 

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
char* digit2Letter(char digit){
    switch(digit){
    case '2':
      return "abc";
    case '3':
      return "def";
    case '4':
      return "ghi";
    case '5':
      return "jkl";
    case '6':
      return "mno";
    case '7':
      return "pqrs";
    case '8':
      return "tuv";
    case '9':
      return "wxyz";
    default:
      return "";
    }
}
 
char** letterCombinations(char* digits, int* returnSize) {
    char** returnArray = NULL;
    if(*digits == '\0') return returnArray;
    
    char* returnElem = malloc(sizeof(char)*sizeof(strlen(digits)));
    returnArray = malloc(sizeof(char*)*1000); 
    backTracking(digits, returnArray, returnSize, returnElem, 0);

    return returnArray;
}

void backTracking(char* digits, char** returnArray, int* returnSize, char* returnElem, int pElem){
    if(*digits == '\0'){
        (*returnSize)++;
        char* elem = malloc(sizeof(char)*pElem);
        memcpy(elem, returnElem, sizeof(char)*pElem);
        elem[pElem] = '\0';
        printf("elem[0] = %d, elem[1] = %d\n",elem[0],elem[1]);
        returnArray[*returnSize-1] = elem;
        return;
    }
    
    char* str = digit2Letter(*digits);
    int len = strlen(str);
    for(int i = 0; i < len; i++){
        returnElem[pElem] = str[i];

        backTracking(digits+1, returnArray, returnSize, returnElem, pElem+1 );
    }
}

 

posted on 2016-04-16 15:32  joannae  阅读(236)  评论(0编辑  收藏  举报

导航