码迷,mamicode.com
首页 > 其他好文 > 详细

17. Letter Combinations of a Phone Number (backtracking)

时间:2016-04-16 16:53:00      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

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 );
    }
}

 

17. Letter Combinations of a Phone Number (backtracking)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/5398527.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!