2-9까지의 숫자를 포함하는 문자열이 있다고 가정합니다. 숫자가 나타낼 수 있는 모든 가능한 문자 조합을 반환해야 합니다. 전화 버튼과 마찬가지로 숫자를 문자로 매핑하는 방법이 아래에 나와 있습니다. 1은 어떤 문자에도 매핑되지 않습니다.
| 1 | 2 b c | 3 디에프 |
| 4 나는 | 5 j k 엘 | 6 아니오 |
| 7 피 q r s | 8 유 v | 9 wxyz |
| * | 0 | # |
예를 들어 주어진 문자열이 "23"이면 가능한 문자열은 ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce ", "cf"]
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
- 재귀적으로 문제를 해결하기 위해 solve라는 배열을 정의합니다.
- solve 메소드는 숫자, 문자, 결과, current_string 및 current_level을 사용합니다. 함수는 다음과 같습니다.
- current_level =자릿수 길이인 경우 결과 뒤에 현재 문자열을 추가하고 반환
- 문자의 모든 문자 i에 대해[숫자[현재_레벨]]
- 해결 수행(숫자, 문자, 결과, current_string + i, current_level + 1)
- 실제 기능은 다음과 같습니다.
- 숫자 길이가 0이면 빈 목록을 반환합니다.
- 숫자와 해당 문자를 문자열로 포함하는 하나의 지도 정의
- 결과:=빈 목록
- 해결 호출(숫자, 문자, 결과, "", 0)
예시(파이썬)
더 나은 이해를 위해 다음 구현을 살펴보겠습니다. −
class Solution(object):
def letterCombinations(self, digits):
if len(digits) == 0:
return []
characters = {2:"abc",3:"def",4:"ghi",5:"jkl",6:"mno",7:"pqrs",8:"tuv",9:"wxyz"}
result = []
self.solve(digits,characters,result)
return result
def solve(self, digits, characters, result, current_string="",current_level = 0):
if current_level == len(digits):
result.append(current_string)
return
for i in characters[int(digits[current_level])]:
self.solve(digits,characters,result,current_string+i,current_level+1)
ob1 = Solution()
print(ob1.letterCombinations("37")) 입력
"37"
출력
["dp","dq","dr","ds","ep","eq","er","es","fp","fq","fr","fs"]