leetcode-电话号码组合(C CODE)

1. 题目

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

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

示例 1:

输入:digits = "23"

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

示例2:

输入:digits = ""

输出:[]

示例 3:

输入:digits = "2"

输出:["a","b","c"]

提示:

0 <= digits.length <= 4

digits[i] 是范围 ['2', '9'] 的一个数字。

2. 编程实现

2.1 思路

  1. 如果输入长度为0,直接返回,没有排列组合;
  2. 如果输入长度是1,那么直接就找对应按键上边的字母输出;
  3. 如果输入长度大于1,例如是2

两个数字的排列组合

可以定义一个map表,把字母与数组做一个关系对应

如:

c 复制代码
typedef struct {
	int num;
	char character[5];
} map_t;

map_t map[10] = {
	{0, {}},
	{1, {}},
	{3, {'a','b','c'}},
	{3, {'d','e','f'}},
	{3, {'g','h','i'}},
	{3, {'j','k','l'}},
	{3, {'m','n','o'}},
	{4, {'p','q','r','s'}},
	{3, {'t','u','v'}},
	{4, {'w','x','y','z'}},
}

2.2 编程实现

c 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int num;
    char letters[5];
} map_t;

map_t map[10] = {
    {0, {}},
    {1, {}},
    {2, {'a', 'b', 'c'}},
    {3, {'d', 'e', 'f'}},
    {4, {'g', 'h', 'i'}},
    {5, {'j', 'k', 'l'}},
    {6, {'m', 'n', 'o'}},
    {7, {'p', 'q', 'r', 's'}},
    {8, {'t', 'u', 'v'}},
    {9, {'w', 'x', 'y', 'z'}},
};

void generateCombinations(char* digits, int index, char* current, char** result, int* count) {
    if (digits[index] == '\0') {
        current[index] = '\0';
        result[(*count)] = strdup(current);
        (*count)++;
    } else {
        int digit = digits[index] - '0';
        for (int i = 0; i < map[digit].num; i++) {
            current[index] = map[digit].letters[i];
            generateCombinations(digits, index + 1, current, result, count);
        }
    }
}

char** letterCombinations(char* digits, int* returnSize) {
    int len = strlen(digits);
    char** result = (char**)malloc(sizeof(char*) * 10000);
    *returnSize = 0;

    if (len == 0) {
        return result;
    }

    char current[5] = {0};
    generateCombinations(digits, 0, current, result, returnSize);

    return result;
}

int main() {
    char* digits = "23"; // 你可以修改这里的输入数字字符串
    int returnSize;
    char** result = letterCombinations(digits, &returnSize);

    for (int i = 0; i < returnSize; i++) {
        printf("%s\n", result[i]);
        free(result[i]);
    }

    free(result);
    return 0;
}
相关推荐
爱编码的小八嘎27 分钟前
C语言完美演绎9-7
c语言
code_pgf31 分钟前
Octo 算法详解-开源通用机器人策略模型技术报告
算法·机器人·开源
澈20740 分钟前
深耕进阶 Day1:C 与 C++ 核心差异 + C++ 入门基石
c语言·开发语言·c++
love530love41 分钟前
Windows Podman Machine 虚拟硬盘迁移完整指南:从 C 盘到非系统盘
c语言·人工智能·windows·podman
嘻嘻哈哈樱桃42 分钟前
牛客经典101题题解集--动态规划
java·数据结构·python·算法·职场和发展·动态规划
Felven44 分钟前
C. Need More Arrays
c语言·开发语言
love530love1 小时前
Podman Machine 虚拟硬盘迁移实战二:用 Junction 把 vhdx 从 C 盘搬到其他盘
c语言·开发语言·人工智能·windows·wsl·podman·podman machine
脱氧核糖核酸__1 小时前
LeetCode热题100——234.回文链表(两种解法)
c++·算法·leetcode·链表
IronMurphy1 小时前
【算法四十二】118. 杨辉三角 198. 打家劫舍
算法
电科一班林耿超1 小时前
第 16 课:动态规划专题(二)—— 子序列与子数组问题:面试最高频的 DP 题型
数据结构·算法·动态规划