美文网首页
[LeetCode 17] Letter Combination

[LeetCode 17] Letter Combination

作者: 灰睛眼蓝 | 来源:发表于2019-05-02 15:24 被阅读0次

Solution

其实就是笛卡尔积

image.png
class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<> ();
        if (digits == null || digits.length () == 0) {
            return result;
        }
        
        Map<String, String> 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<String, String> phoneDigits,
                                           int currentIndex,
                                           String combinationEntry,
                                           List<String> 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 Combination

      本文链接:https://www.haomeiwen.com/subject/mtmnnqtx.html