LeetCode 17. Letter Combinations of a Phone Number 电话号码的字母组合

题目

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

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.

讲解

首先,我们构造一个储存数字和对应字母关系的哈希表。

然后,通过深度优先找到所有的字母组合。

视频教学

Java参考代码

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<>();
        
        if (digits == null || digits.equals("")) {
            return result;
        }
        
        StringBuilder sb = new StringBuilder();
        
        Map<Character, char[]> lettersMap = getLettersMap();    

        letterCombinationsHelper(digits, sb, lettersMap, result);
        
        return result;
    }
    
    private Map<Character, char[]> getLettersMap() {
        Map<Character, char[]> lettersMap = new HashMap<>();
        lettersMap.put('0', new char[]{});
        lettersMap.put('1', new char[]{});                
        lettersMap.put('2', new char[]{'a', 'b', 'c'});                
        lettersMap.put('3', new char[]{'d', 'e', 'f'});                
        lettersMap.put('4', new char[]{'g', 'h', 'i'});    
        lettersMap.put('5', new char[]{'j', 'k', 'l'});    
        lettersMap.put('6', new char[]{'m', 'n', 'o'});    
        lettersMap.put('7', new char[]{'p', 'q', 'r', 's'});    
        lettersMap.put('8', new char[]{'t', 'u', 'v'});    
        lettersMap.put('9', new char[]{'w', 'x', 'y', 'z'});    
        
        return lettersMap;
    }
    
    private void letterCombinationsHelper(String digits, StringBuilder sb, Map<Character, char[]> lettersMap, List<String> result) {
        if (sb.length() == digits.length()) {
            result.add(sb.toString());
            return;
        }      
        
        for (char ch : lettersMap.get(digits.charAt(sb.length()))) {
            sb.append(ch);
            letterCombinationsHelper(digits, sb, lettersMap, result);            
            sb.deleteCharAt(sb.length() - 1);
        }        
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注