LeetCode-17

这次的都不是我写的,感觉有点烦,就没写,下次还是会自己写一遍。C版本的比较麻烦,C++的简洁易懂,推荐大家都看下C++的。 

C版本

char** letterCombinations(char* digits, int* returnSize) {
    char *numLetter[10] ={
        "",
        "",
        "abc",
        "def",
        "ghi",
        "jkl",
        "mno",
        "pqrs",
        "tuv",
        "wxyz"
    };
    int letterLengh[10] = {
        0,0,3,3,3,3,3,4,3,4
    };
    int strNum = 1;
    char **letterResult;
    int numTemp[8] = {0};
    int n = 0,i,j,k;
    int den = 0,col = 0;
    char digitsTemp = 0;
    while(*digits != '\0'){
        numTemp[n] = *digits - '0';
        strNum *= letterLengh[numTemp[n++]];
        digits++;
    }
    
    if(strNum == 1){
        * returnSize = 0;
        return NULL;
    }
    
    *returnSize = strNum;
    letterResult = malloc(sizeof(char *) * strNum);
    
    for(i = 0; i < strNum; i++){
        letterResult[i] = malloc(sizeof(char)*(n+1));
        //memset(letterResult[i],0,n+1);
    }
    den = strNum;
    for(i = 0;i <= n; i++){
        if(letterLengh[numTemp[i]] > 0)
            den /= letterLengh[numTemp[i]];
        for(j = 0; j < strNum;j++){
            if(letterLengh[numTemp[i]] > 0)
                k = j / den % letterLengh[numTemp[i]];
            if(i == n){
                letterResult[j][col] = '\0';
            }
            else letterResult[j][col] = numLetter[numTemp[i]][k];
        }  
        col++;
    }        
    return letterResult;
}

C++版本

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        if (digits.empty()) return {};
        vector<string> res{""};
        string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        for (int i = 0; i < digits.size(); ++i) {
            vector<string> t;
            string str = dict[digits[i] - '0'];
            for (int j = 0; j < str.size(); ++j) {
                for (string s : res) t.push_back(s + str[j]);
            }
            res = t;
        }
        return res;
    }
};

用迭代Iterative来解,在遍历digits中所有的数字时,我们先建立一个临时的字符串数组t,然后跟上面解法的操作一样,通过数字到dict中取出字符串str,然后遍历取出字符串中的所有字符,再遍历当前结果res中的每一个字符串,将字符加到后面,并加入到临时字符串数组t中。取出的字符串str遍历完成后,将临时字符串数组赋值给结果res。

http://www.cnblogs.com/grandyang/p/4452220.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值