본문 바로가기

Programing/Algorithm

[LeetCode] 17. Letter Combinations of a Phone Number

728x90

 

 

 

https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

 

public class Solution
{
    public IList<string> LetterCombinations(string digits)
    {
        if (string.IsNullOrEmpty(digits))
            return new List<string>();


        var map = new Dictionary<char, List<string>>()
        {
            ['2'] = new List<string>() { "a", "b", "c" },
            ['3'] = new List<string>() { "d", "e", "f" },
            ['4'] = new List<string>() { "g", "h", "i" },
            ['5'] = new List<string>() { "j", "k", "l" },
            ['6'] = new List<string>() { "m", "n", "o" },
            ['7'] = new List<string>() { "p", "q", "r", "s" },
            ['8'] = new List<string>() { "t", "u", "v" },
            ['9'] = new List<string>() { "w", "x", "y", "z" },
        };

        IList<string> combinationList = map[digits[0]];

        for (int i = 1; i < digits.Length; i++)
        {
            combinationList = Combine(combinationList, map[digits[i]]);
        }

        return combinationList;
    }

    public IList<string> Combine(IList<string> l1, IList<string> l2)
    {
        IList<string> combinationList = new List<string>();

        for (int i = 0; i < l1.Count; i++)
        {
            for (int j = 0; j < l2.Count; j++)
            {
                combinationList.Add(l1[i] + l2[j]);
            }
        }

        return combinationList;
    }
}

 

 

 

728x90