leetcode做题笔记17

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

leetcode做题笔记17_第1张图片

示例 1:

    输入:digits = "23"
    输出:["ad","ae","af","bd","be","bf","cd","ce","cf"]

思路一:

直接列举可能的情况,根据输入的字符来输出所有情况,验证得此方法可行

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
char phoneMap[11][5] = {"\0", "\0", "abc\0", "def\0", "ghi\0", "jkl\0", "mno\0", "pqrs\0", "tuv\0", "wxyz\0"};

char* digits_tmp;
int digits_size;

char** combinations;
int combinations_size;

char* combination;
int combination_size;

void backtrack(int index) {
    if (index == digits_size) {
        char* tmp = malloc(sizeof(char) * (combination_size + 1));
        memcpy(tmp, combination, sizeof(char) * (combination_size + 1));
        combinations[combinations_size++] = tmp;
    } else {
        char digit = digits_tmp[index];
        char* letters = phoneMap[digit - '0'];
        int len = strlen(letters);
        for (int i = 0; i < len; i++) {
            combination[combination_size++] = letters[i];
            combination[combination_size] = 0;
            backtrack(index + 1);
            combination[--combination_size] = 0;
        }
    }
}

char** letterCombinations(char* digits, int* returnSize) {
    combinations_size = combination_size = 0;
    digits_tmp = digits;
    digits_size = strlen(digits);
    if (digits_size == 0) {
        *returnSize = 0;
        return combinations;
    }
    int num = 1;
    for (int i = 0; i < digits_size; i++) num *= 4;
    combinations = malloc(sizeof(char*) * num);
    combination = malloc(sizeof(char*) * digits_size);
    backtrack(0);
    *returnSize = combinations_size;
    return combinations;
}

时间复杂度为O(3^m+4^n),空间复杂度为O(m+n),m,n为输入字符串中对应3个字母和4个字母的数的个数

本题想到先创建足够大小的二维数组来存放所有可能的情况,再不断输入可能的情况,于是编写了一个backtrack函数来不断输入对应情况,在实际编写的过程中:对于数的处理一开始没想清楚,后面使用循环不断处理才最终编写成功。

问题:对数的处理尚有欠缺

收获:对回溯的理解更深,编写该类问题时更加清楚如何去完成

你可能感兴趣的:(笔记)