Algorithm

17. Letter Combinations of a Phone Number

Doljae 2021. 5. 15. 20:22
 

Letter Combinations of a Phone Number - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

1. DFS

class Solution(object):
    def letterCombinations(self, digits):
        dict1 = {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 digits == "":
            return []
        answer = []

        def dfs(cur, target, result):
            if cur == len(target):
                answer.append(result)
                return
            for char in dict1[int(target[cur])]:
                dfs(cur + 1, target, result + char)

        dfs(0, digits, "")
        return answer

주말은 가볍게.