时间复杂度 - 电话号码的字母组合

时间:2021-03-17 20:13:23

标签: python algorithm time-complexity

这是一个常见的面试问题,我知道已经有很多关于它的问题,但没有一个真正对我有帮助,所以这里是。问题如下:

<块引用>

给定一个数字字符串,返回所有可能的字母组合 数字可以表示是否在标准电话号码键盘上输入。

输入:“23”

输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

我用 python 编写了一个基本的迭代(非递归)解决方案,它似乎有效:

letters = {
    '1': '',
    '2': 'abc',
    '3': 'def',
    '4': 'ghi',
    '5': 'jkl',
    '6': 'mno',
    '7': 'pqrs',
    '8': 'tuv',
    '9': 'wxyz',
    '0': ''
}

def combinations(number_string):

    output = []

    for index, number in enumerate(number_string):
        
        temp_list = []
        for letter in letters[number]:
            if not letters:
                continue

            if index == 0:
                output.append(letter)
            else:
                for combo in output:
                    temp_list.append(combo + letter)

        if temp_list:
             output = temp_list
           
    return output

print(combinations('234'))

但是时间复杂度是多少?为什么?

我知道我正在遍历输入字符串中的每个元素,这立即给了我们至少 O(n)。

然后对于这些元素中的每一个,我将迭代最多 4 个可能的字母组合,所以我知道这让我们得到了 O(4n)。

但是对于每个字母组合,我将迭代所有已经获得的组合(修改每个组合以获得最新的字母)。这是我迷路的地方。

0 个答案:

没有答案
相关问题