LeetCode:17. Letter Combinations of a Phone Number
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
题目的意思就是使用手机上的九宫格输入法输入一串位置,求出这些位置所能组合的所有字符串的情况。
思路一:暴力求解
用列表res保存当前位置之前的所有结果,然后遍历当前位置数字所表示的字符,拼接到res中保存的每个字符串。再赋值给res,最终返回res。
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
ans =[]
numbers = {"2":"abc",
"3":"def",
"4":"ghi",
"5":"jkl",
"6":"mno",
"7":"pqrs",
"8":"tuv",
"9":"wxyz"}
l = len(digits)
if l == 0:
return []
res = []
for c in numbers[digits[0]]:
res.append(c)
if l == 1:
return res
for i in range(1,l):
tmp = []
print(res)
for c in numbers[digits[i]]:
for content in res:
tmp.append(content+c)
res = tmp
return res
思路二:回溯法
和上面的方法总体是一样的,不过是以递归的形式写出的代码而已。就是每一步固定一个位置的字符,然后递归得到后面位置的所有情况,两个部分拼在一起。最终得到所有可能情况。
class Solution:
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
phone = {'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']}
def backtrack(combination, next_digits):
# if there is no more digits to check
if len(next_digits) == 0:
# the combination is done
output.append(combination)
# if there are still digits to check
else:
# iterate over all letters which map
# the next available digit
for letter in phone[next_digits[0]]:
# append the current letter to the combination
# and proceed to the next digits
backtrack(combination + letter, next_digits[1:])
output = []
if digits:
backtrack("", digits)
return output
THE END.