[LeetCode] 17. Letter Combinations of a Phone Number

2020. 12. 27. 20:58·🧇 Algorithm/LeetCode
728x90

Medium

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

 

 

Example 1:

Input: digits = "23"

Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

 

 

Example 2:

Input: digits = ""

Output: []

 

 

나의 코드

class Solution(object):
    res = []  # list of results
    letter = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]

    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        self.res = [] # 결과 배열 초기화
        if digits == "": return []
        self.dfs(digits, 0, []) # DFS

        return self.res

    def dfs(self, d1, cnt, d2):
        """
        :param d1: str 탐색하려는 번호
        :param cnt: int 길이
        :param d2: List[char] 찾은 letters
        """
        if len(d1) == cnt:
            self.res.append("".join(d2)) # add to list res
        else:
        	idx = int(d1[cnt]) # 탐색할 number에서 letter를 찾을 index
            for j in range(len(self.letter[idx])): # letter
                d2.append(self.letter[idx][j]) # add a letter to d2
                self.dfs(d1, cnt + 1, d2) # DFS
                del d2[len(d2) - 1] # 추가했던 letter를 삭제
  • DFS
728x90

'🧇 Algorithm > LeetCode' 카테고리의 다른 글

[LeetCode] 200. Number of Islands  (0) 2020.11.15
'🧇 Algorithm/LeetCode' 카테고리의 다른 글
  • [LeetCode] 200. Number of Islands
soyang.
soyang.
코딩 및 개발 일지를 기록합니다.
  • soyang.
    소소한 코딩일지
    soyang.
  • 전체
    오늘
    어제
  • 링크

    • Github 🐾
    • 포트폴리오 📓 (리뉴얼중)
    • LinkedIn 👩🏻‍💼
  • 공지사항

    • 소소한 코딩일지
  • 블로그 메뉴

    • 방명록
    • 분류 전체보기 (181)
      • 🚩 목표 & 회고 (9)
      • 📓 Papers (10)
      • 🧇 Algorithm (44)
        • 이론 (1)
        • LeetCode (2)
        • 프로그래머스 (30)
        • 백준 (11)
      • 💻 Study (47)
        • 🤖 AI 인공지능 (3)
        • Python 파이썬 (3)
        • Docker 도커 (4)
        • 웹 (20)
        • 안드로이드 (2)
        • JAVA 자바 (1)
        • Firebase (3)
        • Linux 리눅스 (10)
      • 🍪 Projects (2)
      • 🎒 학교 (44)
        • 대학원 도비 (2)
        • 21 동계 모각코: 슈붕팥붕 (13)
        • 21 하계 모각코: 와팬호 (13)
        • 20 동계 모각코: 와팬호 (13)
      • 활동들 (16)
        • 인프런 대학생 LEAF 2기 (9)
        • 2021 Silicon Valley Online .. (7)
  • 태그

    공부
    목표
    error
    모각코
    백준
    Ai
    Artificial Intelligence
    programmers
    알고리즘스터디
    리액트
    인프런대학생Leaf
    Gentoo
    Python
    알고리즘
    프로그래머스
    Algorithm
    코딩테스트
    노마드코더
    Linux
    React
  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
soyang.
[LeetCode] 17. Letter Combinations of a Phone Number
상단으로

티스토리툴바