[LeetCode 17] Letter Combinations of A Phone Number (medium)

Solution

其实就是笛卡尔积

[LeetCode 17] Letter Combinations of A Phone Number (medium)_第1张图片
image.png
class Solution {
    public List letterCombinations(String digits) {
        List result = new ArrayList<> ();
        if (digits == null || digits.length () == 0) {
            return result;
        }
        
        Map phoneDigits = new HashMap<> ();
        phoneDigits.put ("0", "");
        phoneDigits.put ("1", "");
        phoneDigits.put ("2", "abc");
        phoneDigits.put ("3", "def");
        phoneDigits.put ("4", "ghi");
        phoneDigits.put ("5", "jkl");
        phoneDigits.put ("6", "mno");
        phoneDigits.put ("7", "pqrs");
        phoneDigits.put ("8", "tuv");
        phoneDigits.put ("9", "wxyz");
        
        letterCombinationsHelper (digits, phoneDigits, 0, "", result); // currentIndex, combinationEntry
        
        return result;
    }
    
    private void letterCombinationsHelper (String digits,
                                           Map phoneDigits,
                                           int currentIndex,
                                           String combinationEntry,
                                           List result) {
        if (currentIndex == digits.length ()) {
            result.add (combinationEntry);
            return;
        }
        
        String currentLetters = phoneDigits.get (digits.substring (currentIndex, currentIndex + 1));
        
        for (int i = 0; i < currentLetters.length (); i ++) {
            combinationEntry = combinationEntry + currentLetters.substring (i, i + 1);
            letterCombinationsHelper (digits, phoneDigits, currentIndex + 1, combinationEntry, result);
            combinationEntry = combinationEntry.substring (0, combinationEntry.length () - 1);
        }
    }
}

你可能感兴趣的:([LeetCode 17] Letter Combinations of A Phone Number (medium))