程式語言 - LeetCode - C - 17. Letter Combinations of a Phone Number



參考資訊:
https://www.cnblogs.com/grandyang/p/4452220.html

題目:


解答:

int dfs(const char *digits, int pos, int *cidx, char *cbuf, int *ridx, char **rbuf)
{
    int cc = 0;
    const char *BTN[] = {
        "abc", "def",
        "ghi", "jkl", "mno",
        "pqrs", "tuv", "wxyz"
    };

    if (pos >= strlen(digits)) {
        strcpy(rbuf[(*ridx)++], cbuf);

        *cidx -= 1;
        cbuf[*cidx] = 0;
        return 0;
    }

    const char *t = BTN[digits[pos] - '2'];
    int len = strlen(t);

    for (cc = 0; cc < len; cc++) {
        cbuf[(*cidx)++] = t[cc];
        dfs(digits, pos + 1, cidx, cbuf, ridx, rbuf);
    }
    *cidx -= 1;

    return 0;
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
char** letterCombinations(char *digits, int *returnSize)
{
    int cc = 0;
    char **rbuf = NULL;
    char cbuf[256] = { 0 };

    rbuf = malloc(sizeof(char *) * 256);
    for (cc = 0; cc < 256; cc++) {
        rbuf[cc] = malloc(sizeof(char) * 256);
        memset(rbuf[cc], 0, 256);
    }

    *returnSize = 0;
    if (strlen(digits) == 0) {
        return rbuf;
    }

    cc = 0;
    dfs(digits, 0, &cc, cbuf, returnSize, rbuf);

    return rbuf;
}