Fast and simple python solution


  • 2
    Y
    class Solution:
    # @return a list of strings, [s1, s2]
    def letterCombinations(self, digits):
        key={'1':'1','2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz','*':'*','0':'0','#':'#'}
        res=[[]]
        for i in digits:
            nres=[]
            while res:
                l=res.pop()
                for s in key[i]:
                    nres.append(l+[s])
            res=nres
        res=[''.join(l) for l in res if l]
        return res

  • 1
    N

    improved code

        if not digits:
            return []
        result = list(key[digits[0]])
        for i in digits[1:]:
            temp = []
            for x in result:
                for k in key[i]:
                    temp.append(x+k)
            result=temp
        return result

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.