Python dfs code beats 99.82% submissions


  • 0
    K

    0_1472885330630_upload-23c53b39-e1cc-4995-8d85-42a2664f9df1

    class Solution(object):
    def dfs(self,n, str, ans, dic):
    	if len(n) == 0:
    		ans.append(str)
    		str = ""
    	else:
    		d = n[0]
    		for ch in dic[d]:
    			ntr=str+ch
    			self.dfs(n[1:], ntr, ans, dic)
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        dic = {
    		'1':"*",
    		'2':"abc",
    		'3':"def",
    		'4':"ghi",
    		'5':"jkl",
    		'6':"mno",
    		'7':"pqrs",
    		'8':"tuv",
    		'9':"wxyz",
    		'0':" "
    	}
    	ans = []
    	str = ""
    	if len(digits) > 0:
    	    self.dfs(digits, str, ans, dic)
    	return ans

Log in to reply
 

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