The Iterative way is essentially a BSF solution, here is my code


  • 0
    G
        public List<String> letterCombinations(String digits) {
             Queue<String> ans = new LinkedList<String>();
             if (digits.length() == 0) { return (List) ans; }
             String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
             ans.add("");
             for (int i = 0; i < digits.length(); i++) {
                 int index = Character.getNumericValue(digits.charAt(i));
                 int size = ans.size();
                 for (int j = 0; j < size; j++) {
                     String str = ans.poll();
                     for (int k = 0; k < mapping[index].length(); k++) {           
                        ans.offer(str + mapping[index].charAt(k));   
                     }
                 }
             }
            return (List) ans;
        }
    

Log in to reply
 

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