DFS电话号码问题,及通用解题模板

# 1.终止条件  2.当前层处理  3.递归下一层
map = {
    2: "abc",
    3: "def",
    4: "ghi",
    5: "jkl",
    6: "mno",
    7: "pqrs",
    8: "tuv",
    9: "wxyz"
}
res = []


def phone_num(target: str, depth: int, string: str):
    '''
    type target: 输入的数字
    type depth: 深度
    rtype:返回所有组合 List[str]
    '''
    # 终止条件
    # 终止条件也可以不这么写,用切片的方式同样可以实现
    if depth+1 > len(target):
        res.append(string)
    # 这里必须加else
    else:
        # 当前层处理
        x = target[depth]
        loop = map[int(x)]
        for i in loop:
            # 开始递归
            # 用string这个参数将上一层的结果带到下一层
            phone_num(target, depth+1, string+i)


phone_num("23", 0, "")
print(res)
发布了140 篇原创文章 · 获赞 53 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44291044/article/details/105178510