Letter Combinations of a Phone Number

Given a string containing digits from 2-9inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

 

 

Solution:

Do the backtracking to find all letter combinations.

ex.
       /        |        \
      a         b         c
    / | \     / | \     / | \
   d  e  f   d  e  f   d  e  f
  • If no more digit (layer) needs to be added, means we finish one of the combinations.
  • Else, iterate (for loop) all letters of next digit (layer):
    • Current String += one of the letters of next digit
    • Go to the next digit.  (backtracking)

 

class Solution {
    
    Map<Character, String> map = new HashMap<Character, String>() {{
        put('2', "abc");
        put('3', "def");
        put('4', "ghi");
        put('5', "jkl");
        put('6', "mno");
        put('7', "pqrs");
        put('8', "tuv");
        put('9', "wxyz");
    }};
    
    List<String> res = new ArrayList<>();
    
    public List<String> letterCombinations(String digits) {
        if (digits.length() != 0) {
            dfs("", 0, digits);
        }
        return res;
    }
    
    public void dfs(String curString, int idx, String digits) {
        if (idx == digits.length()) {
            res.add(curString);
        } else {
            for (char ch : map.get(digits.charAt(idx)).toCharArray()) {
                curString += ch;
                dfs(curString, idx + 1, digits);
                curString = curString.substring(0, curString.length() - 1);
            }
        }
    }
}

Time complexity : 

Space complexity :

Leave a comment