17 Letter Combinations of a Phone Number

1. Question

Given a digit string, 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.

Input:
Digit string "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.

2. Implementation

(1) Backtracking

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> res = new ArrayList<>();

        if (digits == null || digits.length() == 0) {
            return res;
        }

        String[] keys = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

        StringBuilder combination = new StringBuilder();
        getLetterCombinations(digits, 0, combination, keys, res);
        return res;
    }

    public void getLetterCombinations(String digits, int pos, StringBuilder combination, String[] keys, List<String> res) {
        if (pos == digits.length()) {
            res.add(combination.toString());
            return;
        }

        String key  = keys[digits.charAt(pos) - '0'];
        for (int i = 0; i < key.length(); i++) {
            combination.append(key.charAt(i));
            getLetterCombinations(digits, pos + 1, combination, keys, res);
            combination.setLength(combination.length() - 1);
        }
    }
}

3. Time & Space Complexity

时间复杂度O(L^n), L为digits的长度, n为一个数字对应的最长letters的长度, 空间复杂度O(L^n)

Last updated