巴拉巴拉又开始刷题了,进入正题
题目:17. 电话号码的字母组合
思路:深度优先搜索(DFS)
代码:
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
if not digits:
return []
phonemap = {
"2":"abc",
"3":"def",
"4":"ghi",
"5":"jkl",
"6":"mno",
"7":"pqrs",
"8":"tuv",
"9":"wxyz",
}
def backpack(index):
if index == len(digits):
return combinations.append("".join(combination))
else:
digit = digits[index]
for letter in phonemap[digit]:
combination.append(letter)
backpack(index+1)
combination.pop()
combination = []
combinations = []
backpack(0)
return combinations
参考:电话号码的字母组合
题解:凡是关于全排列的问题都可以套用DFS,DFS的公式是:
def dfs(index):
if len(stack)==n:
输出组合:print(path)
for (所有组合可选的选项;n):
队列追加元素:stack.append()
走到下一层:dfs(index+1)
恢复现场:path(index) = 0 state[i]=false
对于全排列的数字组合而言,只需要在可选的数字中间进行for循环即可,但是对于此题,由于选取几个数字就意味着多几种可选的选项,因此要在for循环外面将所有可选的选项遍历出来,此题相对全排列而言就是多了一步遍历所有字母提供的选项。
注意点:①字母的长度即为输出的边界条件
②DFS之前多加一个索引全部的选项