gpt4 book ai didi

c# - 递归 for 循环代码的时间复杂度

转载 作者:行者123 更新时间:2023-11-30 18:02:09 24 4
gpt4 key购买 nike

我有这个代码,

void Generate(List<string> comb, string prefix, string remaining)
{
int currentDigit = Int32.Parse(remaining.Substring(0, 1));

if (remaining.Length == 1)
{
for (int i = 0; i < dictionary[currentDigit].Length; i++)
{
comb.Add(prefix + dictionary[currentDigit][i]);
}
}
else
{
for (int i = 0; i < dictionary[currentDigit].Length; i++)
{
Generate(comb, prefix + dictionary[currentDigit][i], remaining.Substring(1));
}
}
}

上述代码的时间复杂度是多少?

它生成是 O(n) 并且它本身正在执行 n 次所以 O(n^2)?

字典是 len = 10 并且有电话键盘存储它。2 = "abc"等。

这段代码的初始调用会像

生成(新列表(),“”,“12345”);

谢谢。

最佳答案

假设字典大小为 m,输入字符串大小为 n(剩余)这将是:

T(1) = m + constant;
T(n) = m T(n-1) + O(n) ==> T(n) = O(m^n)

实际上每次运行else部分,你都会运行m次,O(n)的函数。

关于c# - 递归 for 循环代码的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8288233/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com