学渣带你刷Leetcode0017. 电话号码的字母组合

题目描述

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

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

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

白话题目:

2-9都代表不同的字母,按了建之后可以输出的不同的字母组合。每个字母都是取自每个数字的,数字可以重复出现23是合法输入,22也是合法输入,23423422222也是合法输入。

算法:

纯暴力肯定爆表

顺序刷题的第一个DFS算法,深度优先搜索

以2、3为例

2的a,之后3的d,e,f;

2的b,之后3的d,e,f;

2的c,之后3的d,e,f;

详细解释关注 B站  【C语言全代码】学渣带你刷Leetcode 不走丢 https://www.bilibili.com/video/BV1C7411y7gB

C语言完全代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
void dfs(char *digits, char *str, int ind, char letter[][5], char **res, int *returnSize) {
    if (digits[ind] == '\0') {   //
        str[ind] = '\0';
        strcpy(res[*returnSize], str);
      //  printf("%s\n",str);
        (*returnSize)++;
        return ;
    }
    int d = digits[ind] - '0';   //用输入字符串的ind位取digits里面的整数  例如2  ,d=2
    int i = 0;
    while (letter[d][i] != '\0') {   //不为空的话就进行
        str[ind] = letter[d][i];
        //printf("%d ",d);
        dfs(digits, str, ind + 1, letter, res, returnSize);
        i++;
    }
}

char ** letterCombinations(char * digits, int* returnSize){

    *returnSize = 0;   //初始返回个数为0;
    if (digits[0] == '\0') return digits;
    char letter[][5] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    int len = strlen(digits);
    int count = 1;
    int i,j;
    for (i = 0; i < len; i++) {   //4的n次方个
        count *= 4;
    }
    char **res = (char **)malloc(sizeof(char *) * count);
    for ( i = 0; i < count; i++) {
        res[i] = (char *)malloc(sizeof(char) * (len + 1));  //行的大小
        res[i][len] = '\0';
    }
    //printf("count===%d\n",count);
    char *str = (char *)malloc(sizeof(char) * (len + 1));  //临时存放结果的
    dfs(digits, str, 0, letter, res, returnSize);
    return res;
}
int main()
{

    printf("可以输入的测试数据  23 \n");
    char  *digits;
    digits=(char *)malloc(sizeof(char));
    gets(digits);
    int length=strlen(digits);

    int returnSize;
    int i,j;
    char **result=letterCombinations(digits,&returnSize);
    for (i = 0; i < returnSize; i++)
    {
        //for ( j = 0; j < length; j++)
       // {
       //     printf("%c", result[i][j]);
       // }
        printf("\n");
        printf("%s",*(result+i));
    }
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值