C# recursive implementation


  • 0
    C

    Add each character for a digit to previous generated list

        private static string[] mapping = new string[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
        public IList<string> LetterCombinations2(string digits)
        {
            List<string> l = new List<string>();
            return Comb(l, digits, 0);
        }
    
        private IList<string> Comb(IList<string> cres, string digits, int pos)
        {
            if (pos == digits.Length)
            {
                return cres;
            }
    
            IList<string> result = new List<string>();
    
            foreach (var c in mapping[digits[pos] - '0'])
            {
                if (cres.Count == 0)
                {
                    result.Add(c.ToString());
                }
                else
                {
                    foreach (var item in cres)
                    {
                        result.Add(item + c);
                    }
                }
            }
    
            return Comb(result, digits, pos + 1);
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.