Letter Combinations of a Phone Number

题目
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"].
Letter Combinations of a Phone Number_第1张图片
image.png

答案

class Solution {
    public List letterCombinations(String digits) {
        List list = new ArrayList();
        HashMap 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");
        recur(digits, 0, "", list, map);
        return list;
    }
    
    public void recur(String digits, int curr_index, String curr_letters, List list, HashMap map) {
        if(curr_index == digits.length()) {
            if(!curr_letters.equals(""))
                list.add(curr_letters);
            return;
        }
        char digit = digits.charAt(curr_index);
        if(digit == '0' || digit == '1') {
            recur(digits, curr_index + 1, curr_letters, list, map);
            return;
        }
        // Three choices
        String s = map.get(digit);
        for(int i = 0; i < s.length(); i++) {
            recur(digits, curr_index + 1, curr_letters + s.charAt(i), list, map);
        }
    }
}


你可能感兴趣的:(Letter Combinations of a Phone Number)