C# recursion,beats 96%


  • 0
    public class Solution
    {
        class keyboard
        {
            public char letter;
            public int posSitu;
        }
        List<string> ans = new List<string>();
        List<keyboard> letters = new List<keyboard>();
        public IList<string> LetterCombinations(string digits)
        {
            for (int i = 0; i < digits.Length; i++)
            {
                switch (digits[i])
                {
                    case '2':
                        letters.Add(new keyboard() { letter = 'a', posSitu = 3 });
                        break;
                    case '3':
                        letters.Add(new keyboard() { letter = 'd', posSitu = 3 });
                        break;
                    case '4':
                        letters.Add(new keyboard() { letter = 'g', posSitu = 3 });
                        break;
                    case '5':
                        letters.Add(new keyboard() { letter = 'j', posSitu = 3 });
                        break;
                    case '6':
                        letters.Add(new keyboard() { letter = 'm', posSitu = 3 });
                        break;
                    case '7':
                        letters.Add(new keyboard() { letter = 'p', posSitu = 4 });
                        break;
                    case '8':
                        letters.Add(new keyboard() { letter = 't', posSitu = 3 });
                        break;
                    case '9':
                        letters.Add(new keyboard() { letter = 'w', posSitu = 4 });
                        break;
                    default :
                        return ans;
                }
    
            }
            getString(0, "");
            return ans;
        }
        public void getString(int indexOfLetter,string now)
        {
            if(indexOfLetter<letters.Count)
            {
                char nowChar = letters[indexOfLetter].letter;
                for (int i = 0; i < letters[indexOfLetter].posSitu; i++)
                {
                    getString(indexOfLetter + 1, now + nowChar);
                    if (indexOfLetter==letters.Count-1)
                    {
                        ans.Add(now + nowChar);
                    }
                    nowChar++;
                }
            }
        }
    }

Log in to reply
 

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