Python depth first search + dictionary


  • 1
    class Solution(object):
        def letterCombinations(self, digits):
            if not digits:
                return []
            answer = []
            dic = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6':'mno', '7':'pqrs', '8':'tuv', '9':'wxyz'}
            def dfs(idx, ans):
                if idx == len(digits):
                    answer.append(ans)
                    return 
                list = dic[digits[idx]]
                for c in list:
                    dfs(idx + 1, ans + c)
            dfs(0, '')
            return answer
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.