【LeetCode】17.电话号码的字母组合

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time: 2019/3/13
# @Author: xfLi
# The file...

"""
问题分析:
很显然是,组合问题使用回溯法,递归求解,可以使用深度优先(dfs)的思想。
(1)用 index 记录 digits 字符串中的字符索引。
(2)用 paths 表示走过的字符,走到头,就保存到 res, 然后回溯当上一层,继续。
(3)这个过程相当于深度优先搜索。
"""

def letterCombinations(digits):
    if not digits: return []
    dict = {'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']}
    def dfs(digits=digits, index=0, paths=''):
        if len(digits) == index:
            res.append(paths)
            return
        for var in (dict[digits[index]]):
            dfs(digits, index+1, paths+var)
    res = []
    dfs()
    return res

if __name__ == '__main__':
    digits = '23'
    result = letterCombinations(digits)
    print(result)

猜你喜欢

转载自blog.csdn.net/qq_30159015/article/details/88558801