[英]Time complexity of recursive algorithm with two recursive calls
我正在嘗試分析一種遞歸算法的時間復雜度,該算法可解決生成漢明距離t問題內的所有位序列 。 算法是這樣的:
// str is the bitstring, i the current length, and changesLeft the
// desired Hamming distance (see linked question for more)
void magic(char* str, int i, int changesLeft) {
if (changesLeft == 0) {
// assume that this is constant
printf("%s\n", str);
return;
}
if (i < 0) return;
// flip current bit
str[i] = str[i] == '0' ? '1' : '0';
magic(str, i-1, changesLeft-1);
// or don't flip it (flip it again to undo)
str[i] = str[i] == '0' ? '1' : '0';
magic(str, i-1, changesLeft);
}
該算法的時間復雜度是多少?
我對此感到非常生銹,這是我的嘗試,我覺得這與事實不符:
t(0) = 1
t(n) = 2t(n - 1) + c
t(n) = t(n - 1) + c
= t(n - 2) + c + c
= ...
= (n - 1) * c + 1
~= O(n)
其中n
是位串的長度。
它是指數的 :
t(0) = 1
t(n) = 2 t(n - 1) + c
t(n) = 2 (2 t(n - 2) + c) + c = 4 t (n - 2) + 3 c
= 2 (2 (2 t(n - 3) + c) + c) + c = 8 t (n - 3) + 7 c
= ...
= 2^i t(n-i) + (2^i - 1) c [at any step i]
= ...
= 2^n t(0) + (2^n - 1) c = 2^n + (2^n - 1) c
~= O(2^n)
或者,使用WolframAlpha: https ://www.wolframalpha.com/input/ ? i = t(0)%3D1,+t(n)%3D2+t(n-1)+%2B+c
它呈指數級的原因是您的遞歸調用將問題大小減小了1,但是您要進行兩個遞歸調用。 您的遞歸調用正在形成一棵二叉樹。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.