LeetCode #17 Letter Combinations of a Phone Number C# Solution

本文介绍了一种使用回溯算法解决数字字符串转字母组合的方法。通过建立数字与字母的映射关系,实现了从输入的数字字符串到所有可能的字母组合的转换。示例中详细展示了如何针对特定输入生成所有可能的输出。

Given a digit string, return all possible letter combinations that the number could represent.
ex:
Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

回溯算法,暴力搜索= =

ugly C# Code

    public class Solution
    {
        Dictionary<char, List<char>> k = new Dictionary<char, List<char>>
        {
            { '2', new List<char>{ 'a','b','c'} },
            { '3', new List<char>{ 'd','e','f'} },
            { '4', new List<char>{ 'g','h','i'} },
            { '5', new List<char>{ 'j','k','l'} },
            { '6', new List<char>{ 'm','n','o'} },
            { '7', new List<char>{ 'p','q','r','s'} },
            { '8', new List<char>{ 't','u','v'} },
            { '9', new List<char>{ 'w','x','y','z'} }
        };
        IList<string> anss = new List<string>();
        public IList<string> LetterCombinations(string digits)
        {
            if (digits == "") return new List<string> { };
            string ans = "";
            calc(digits, 0, digits.Length, ans);
            return anss;
        }

        private string calc(string d, int p, int max, string ans)
        {
            if (p == max)
            {
                anss.Add(ans);
                return ans;
            }
            foreach (char c in k[d[p]])
            {
                calc(d, p + 1, max, ans + c);
            }
            return ans;
        }
    }

这里写图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值