需求
給定一個僅包含數字 2-9 的字符串,返回所有它能表示的字母組合。
數字到字母的映射,與電話按鍵相同。注意 1 不對應任何字母。
示例
輸入:"23"
輸出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
說明:盡管上面的答案是按字典序排列的,但是你可以任意選擇答案輸出的順序。
方法一:遍歷上次的組合結果,逐個合并
首先判斷特殊情況,數字長度為0或數字為空時,直接返回空列表[];
基于數字和字母構建字典,遍歷digits,獲取數字對應的字母組合,遍歷字母組合,同時遍歷上次組合的結果,合并后添加到中間結果,一個數字遍歷完成,對組合結果重新賦值為最新的中間結果;
特別地,初始化組合結果時,不能為空列表,如果為空列表,則不會執行遍歷組合結果的代碼段,本例中需要拼接字符,所以設置為一個空字符,對結果沒有影響;
參考代碼
def num_letter_combinations(digits):
if len(digits) == 0 or digits == '': return []
num_letter = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
res = ['']
for d in digits:
if d in num_letter.keys():
tmp = []
for s in num_letter[d]:
for r in res:
tmp.append(s + r)
res = tmp
return res
digits = '23'
print(num_letter_combinations(digits))
['da', 'db', 'dc', 'ea', 'eb', 'ec', 'fa', 'fb', 'fc']
方法二:倒序遍歷 + extend()
本方法的實現邏輯和方法一基本一致,主要區別是使用了python內置的追加元素的函數
extend()
,無需顯式地對上次的組合結果進行遍歷,就可以逐個(而不是作為整體)與字母拼接后,形成新的組合結果;由于digits的輸入順序,會影響最后的組合順序,在遍歷digits和對應的字母時,需要進行倒序遍歷;
參考代碼
def num_letter_combinations(digits):
if len(digits) == 0 or digits == '': return []
num_letter = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
res = ['']
for d in digits:
if d not in num_letter.keys(): return []
else:
tmp = []
for s in num_letter[d]:
tmp.extend(s + x for x in res)
res = tmp
return res
digits = '23'
print(num_letter_combinations(digits))
['da', 'db', 'dc', 'ea', 'eb', 'ec', 'fa', 'fb', 'fc']