leetcode -- Letter Combinations of a Phone Number -- 重点

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

先手工枚举,构造解空间树.标准dfs求解。

class Solution(object):

    def dfs(self, digits, target_lvl, mydict, subres, res):
        lvl = len(subres)
        if lvl == target_lvl:
            if subres:
                res.append(subres[:])
            return
        else:

            for x in mydict[digits[lvl]]:#子节点为下一个数字对应的每个字母
                self.dfs(digits, target_lvl, mydict, subres + x, res)


    def letterCombinations(self, digits):
        """ :type digits: str :rtype: List[str] """
        mydict = {'2':['a','b','c'],
        '3':['d','e','f'],
        '4':['g','h','i'],
        '5':['j','k','l'],
        '6':['m','n','o'],
        '7':['p','q','r','s'],
        '8':['t','u','v'],
        '9':['w','x','y','z']
        }
        res = []
        self.dfs(digits, len(digits), mydict, "",res)
        return res

自己重写code

这里的子集树,每一层对应一个数字的三个字母,其子节点为下一个数字的三个字母。

class Solution(object):

    def dfs(self, candidates, level, mydict, subres, res):
        if level == len(candidates):
            res.append(subres)
            return#不要忘记return

        for j in mydict[candidates[level]]:#每一个level对应一个数字
            self.dfs(candidates, level + 1, mydict, subres + j, res)

    def letterCombinations(self, digits):
        """ :type digits: str :rtype: List[str] """
        mydict = {'2':['a','b','c'],
        '3':['d','e','f'],
        '4':['g','h','i'],
        '5':['j','k','l'],
        '6':['m','n','o'],
        '7':['p','q','r','s'],
        '8':['t','u','v'],
        '9':['w','x','y','z']
        }
        if not digits: return []
        res = []
        self.dfs(digits, 0, mydict, '', res)
        return res

你可能感兴趣的:(LeetCode)