Python中的電話號碼字母組合
假設我們有一個字串,包含從2到9(包含2和9)的數字。我們需要返回該數字可以表示的所有可能的字母組合。數字到字母的對映(就像電話按鍵一樣)如下所示。請注意,1不對映到任何字母。
| 1 | 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 |
| * | 0 | # |
例如,如果給定的字串是“23”,則可能的字串將是[“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]。
為了解決這個問題,我們將遵循以下步驟:
- 定義一個名為solve的陣列,以遞迴方式解決問題。
- solve方法接受數字、字元、結果、當前字串和當前級別,函式將如下所示:
- 如果當前級別等於數字的長度,則在結果之後添加當前字串,然後返回。
- 對於characters[digits[current_level]]中的所有字元i:
- 執行solve(digits, characters, result, current_string + i, current_level + 1)
- 實際函式將如下所示:
- 如果數字長度為0,則返回空列表。
- 定義一個map來儲存數字和對應的字元(作為字串)。
- result := 空列表
- 呼叫solve(digits, characters, result, “”, 0)
示例(Python)
讓我們看下面的實現,以便更好地理解:
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"]
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP