Leetcode 17. 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.

Leetcode 17. Letter Combinations of a Phone Number_第1张图片

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.

分析

手机上的拼音输入法,每个数字键代表多个字母。
根据输入的数字串,返回可能的字符串
下面的C代码已通过。
先初始化二维字符数组,然后如果出现0或者1,或者数字串为空,就直接返回空。然后再依次递归判断接下来的字符,根据不同的数字表示不同的字符,之后在找到最后一个字符的时候,将该字符串存入结果字符串数组中。

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */

void combination(char *digits,int digitsLength,char ** ans,int *returnSize,char *temp,int tempLength)
{
    if(digits[digitsLength]==NULL)
    {
        char * ansTemp=(char *)malloc(sizeof(char)*1000);
        int i=0;
        for(i=0;i

当然还有更简单的方法,先处理前两个数字尽可能多的字符串,之后依次根据后面的数字再组成更多的字符串,可能需要重复赋值,但是相对的内存空间消耗较少。而我的方法多次递归,消耗大量栈空间。

你可能感兴趣的:(Leetcode 17. Letter Combinations of a Phone Number)