• LeetCode //C - 17. Letter Combinations of a Phone Number


    17. Letter Combinations of a Phone Number

    Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

    A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
    在这里插入图片描述
     

    Example 1:

    Input: digits = “23”
    Output: [“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]

    Example 2:

    Input: digits = “”
    Output: []

    Example 3:

    Input: digits = “2”
    Output: [“a”,“b”,“c”]

    Constraints:
    • 0 <= digits.length <= 4
    • digits[i] is a digit in the range [‘2’, ‘9’].

    From: LeetCode
    Link: 17. Letter Combinations of a Phone Number


    Solution:

    Ideas:

    1. Mapping:

    • A 2D array mapping is used to map digits from ‘2’ to ‘9’ to their corresponding letters.

    2. Calculate Total Combinations:

    • The variable total is used to calculate the total number of combinations. This is done by multiplying the lengths of the strings that each digit maps to. For the string “23”, this would be 3×3=9 (since “2” maps to “abc” and “3” maps to “def”).

    3. Generate Combinations:

    • The main logic is in this part. We iterate i from 0 to total-1 and for each value of i, we generate one combination.
    • For each digit in the input, we determine which letter it should map to using modular arithmetic. This is essentially converting i into a number in our mixed-radix system.
    • We use a variable temp to keep track of the current radix. For each digit, we use the formula mapping[digits[j] - ‘2’][(i / temp) % len] to determine which letter to pick. The division by temp shifts our focus to the correct digit position, and the modulo operation (% len) gives us the index of the letter to use for the current digit.
    • After picking the letter, we multiply temp by len to update the radix for the next position.

    4. Main Function:

    • This is just a demonstration of how to use the letterCombinations function. It calls the function with the input “23”, prints the resulting combinations, and then frees the allocated memory.
    Code:
    /**
     * Note: The returned array must be malloced, assume caller calls free().
     */
    char ** letterCombinations(char * digits, int* returnSize) {
        if (!digits || strlen(digits) == 0) {
            *returnSize = 0;
            return NULL;
        }
        
        char* mapping[] = {
            "abc", "def", "ghi", "jkl",
            "mno", "pqrs", "tuv", "wxyz"
        };
        
        int total = 1;
        for (int i = 0; i < strlen(digits); i++) {
            total *= strlen(mapping[digits[i] - '2']);
        }
        
        *returnSize = total;
        char** result = (char**) malloc(total * sizeof(char*));
        
        for (int i = 0; i < total; i++) {
            result[i] = (char*) malloc((strlen(digits) + 1) * sizeof(char));
            int temp = 1;
            for (int j = 0; j < strlen(digits); j++) {
                int len = strlen(mapping[digits[j] - '2']);
                result[i][j] = mapping[digits[j] - '2'][(i / temp) % len];
                temp *= len;
            }
            result[i][strlen(digits)] = '\0';
        }
        
        return result;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
  • 相关阅读:
    Security思想项目总结
    DBeaver连接数据库报错:Public Key Retrieval is not allowed 的解决方案
    圆梦腾讯之后,我收集整理了这份“2022Java 常见面试真题汇总
    【OpenCV 例程200篇】209. HSV 颜色空间的彩色图像分割
    7月VR大数据:Quest 2占比突破50%,Pico Neo 3较上月大幅涨幅
    Maven execution terminated abnormally (exit code 1) 创建Maven项目时报错解决方法
    【C语言】每日一题(半月斩)——day2
    解决nacos集群搭建,服务注册失败
    大数据必学Java基础(六十三):COW并发容器讲解
    第一章操作系统引论
  • 原文地址:https://blog.csdn.net/navicheung/article/details/133666197