17. 电话号码的字母组合


官方链接

https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

解法一

backtracking

class Solution {

    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) return 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");

        List<String> result = new ArrayList<>();
        _generate(result, map, digits, 0, "");
        return result;

    }


  public void _generate(List<String> result, Map<Character, String> map, String digits, int index, String s) {
    // terminator
    if (index == digits .length()) {
      result.add(s);
      return;
    }
    // process
    String letters = map.get(digits.charAt(index));
    for (int i = 0; i < letters.length(); i++) {
        // drill down
        _generate(result, map, digits, index + 1, s + letters.charAt(i));    
    }
    // reverse states
  }
}
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
      if not digits:
        return []

      self.result = []
      self.d = {
        '2': 'abc',
        '3': 'def',
        '4': 'ghi',
        '5': 'jkl',
        '6': 'mno',
        '7': 'pqrs',
        '8': 'tuv',
        '9': 'wxyz'
      }

      self.dfs(digits, [], 0)
      return self.result

    def dfs(self, digits, temp, index):
      if len(temp) == len(digits):
        self.result.append("".join(x for x in temp))
        return

      for c in self.d[digits[index]]:
        temp.append(c)
        self.dfs(digits, temp, index+1)
        temp.pop()