Leetcode 17关于python字典关键问题的问题

2024-09-29 01:27:23 发布

您现在位置:Python中文网/ 问答频道 /正文

当我做leetcode的第17题时,它被描述为: 给定一个包含2-9(含2-9)数字的字符串,返回该数字可能表示的所有可能的字母组合。按任意顺序返回答案。”

那么,与数字对应的所有字母的字典可以描述为:

n_dict = {"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"]}

我的解决方案是:

self.output = []

    def helper(number):
        if not number: return
        if self.output:
            times = len(self.output)
            #print(n_dict[number[0]])
            for _ in range(0, times):
                item = self.output.pop(0)
                for char in n_dict[number[0]]:
                    self.output.append(item+char)
            return
        else:
            self.output = n_dict[number[0]]
        helper(number[1:])
        return
    
    helper(digits)
    return self.output
    

这适用于“23”、“567”、“3267”和其他非重复数字组合。 然而,当输入变成“22”甚至“232”时,运行时间变得疯狂,然后我试图找出原因,发生了一件非常奇怪的事情。我在上面一行插入了print命令,输出如下:

['b', 'c']
['b', 'c', 'ab']
['b', 'c', 'ab', 'ac']
['b', 'c', 'ab', 'ac', 'aab']
['b', 'c', 'ab', 'ac', 'aab', 'aac']
['b', 'c', 'ab', 'ac', 'aab', 'aac', 'aaab']
['b', 'c', 'ab', 'ac', 'aab', 'aac', 'aaab', 'aaac']
['b', 'c', 'ab', 'ac', 'aab', 'aac', 'aaab', 'aaac', 'aaaab']
['b', 'c', 'ab', 'ac', 'aab', 'aac', 'aaab', 'aaac', 'aaaab', 'aaaac']

这意味着n_dict[“2”]只包含[“b”,“c”]而不是[“a”,“b”,“c”]。除此之外,for循环变得无限,而不是在n_dict[“2”]的长度范围内。 有人知道这是怎么发生的吗?非常感谢


Tags: selfhelpernumberforoutputreturnifab
1条回答
网友
1楼 · 发布于 2024-09-29 01:27:23
  • 算法中可能有错误

  • 这将使用字典类似地传递LeetCode:

class Solution:
    def letterCombinations(self, digits):
        if digits == '':
            return []
        d = {
        '2': 'abc',
        '3': 'def',
        '4': 'ghi',
        '5': 'jkl',
        '6': 'mno',
        '7': 'pqrs',
        '8': 'tuv',
        '9': 'wxyz'
        }
        res = ['']
        for digit in digits:
            temp = []
            for r in res:
                for item in d[digit]:
                    temp.append(r + item)
                res = temp
        return res

相关问题 更多 >