如果0代表"abc",1代表"def",2代表"ghi",3代表"jkl",4代表"mno",5代表"pqr",6代表"st",7代表"uv",8代表"wx",9代表"yz",输入任意长度的0~9的数字,从每个数字对应的字母中选一个组成字符串有哪些,怎么用python代码实现
时间: 2023-09-03 20:09:25 浏览: 183
Bản ghi Mới 7.m4a
可以使用递归的方式实现:
```python
def letter_combinations(digits):
if not digits:
return []
digit_to_letter = {
"0": "abc",
"1": "def",
"2": "ghi",
"3": "jkl",
"4": "mno",
"5": "pqr",
"6": "st",
"7": "uv",
"8": "wx",
"9": "yz",
}
results = []
def dfs(index, prefix):
if index == len(digits):
results.append(prefix)
return
for letter in digit_to_letter[digits[index]]:
dfs(index+1, prefix+letter)
dfs(0, "")
return results
```
使用示例:
```python
print(letter_combinations("23")) # ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
```
阅读全文