欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Leetcode 17. Letter Combinations of a Phone Number(python)

程序员文章站 2022-07-15 12:42:51
...

Leetcode 17. Letter Combinations of a Phone Number

题目

Leetcode 17. Letter Combinations of a Phone Number(python)

解析

这题实际上是一个无重复combination的模板题,只需要对1做一下特殊处理即可
关于combination和permutation的总结,看这里

代码:

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        def backtracking(comb,level):
            if len(comb)==length:
                ans.append(comb[:])
            
            for i in range(level,len(digits)):
                if digits[level]=='1':
                    continue
                for c in d[digits[i]]:
                    #comb.appned(c)
                    backtracking(comb+c,i+1)
                    #comb.pop()
                    
        
        count_1 = 0
        for digit in digits:
            if digit == '1':
                count_1 += 1
        
        d = {'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']}
        if not digits:
            return []
        ans = []
        length = len(digits)-count_1
        backtracking('',0)
        return ans