Weikoi

导航

Leetcode-017-电话号码的字母组合

全排列问题。

class Solution {
    public List<String> letterCombinations(String digits) {
        Map<Character, String> dict = new HashMap<>();
        dict.put('2', "abc");
        dict.put('3', "def");
        dict.put('4', "ghi");
        dict.put('5', "jkl");
        dict.put('6', "mno");
        dict.put('7', "pqrs");
        dict.put('8', "tuv");
        dict.put('9', "wxyz");

        List<String> res = new ArrayList<>();
        if(digits.length()==0){return res;}
        res.add("");
        for(Character d:digits.toCharArray()){
            List<String> demo = new ArrayList<>();
            for(Character c:dict.get(d).toCharArray()){
                for(String s:res){
                    demo.add(new StringBuilder(s).append(c).toString());
                }
            }
            res = demo;
        }
        return res;
    }
}

 

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        maps = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
        if not digits:return []
        res = ['']
        for d in digits:
            demo= []
            for c in maps[d]:
                demo += [ele + c for ele in res]
            res = demo
        return res

 

posted on 2020-03-09 01:30  Weikoi  阅读(140)  评论(0编辑  收藏  举报