17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, 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

经典Backtracking题目

Complexity

Code

class Solution {
    public List<String> letterCombinations(String digits) {
        if(digits == null || digits.length() == 0)
            return new ArrayList<>();
        List<String> res = new ArrayList<>();
        Map<Character, String> map = new HashMap<>();
        map.put('2', "abc");
        map.put('3', "def");
        map.put('4', "ghi");
        map.put('5', "jkl");
        map.put('6', "mno");
        map.put('7', "pqrs");
        map.put('8', "tuv");
        map.put('9', "wxyz");
        helper(digits, 0, new StringBuilder(), res, map);
        return res;
    
    }
    public void helper(String digits, int start, StringBuilder sb, List<String> res, Map<Character, String> map){
        if(start >= digits.length()){
            res.add(sb.toString());
            return;
        }
        
        String s = map.get(digits.charAt(start));
        for(Character c : s.toCharArray()){
            sb.append(c);
            helper(digits, start + 1, sb, res, map);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}