[英]Calculating worst-case run time complexity of recursive algorithm
在clasas中,我開始學習如何計算各種算法的運行時復雜度函數,並且發現它很困難。 我試圖在下面計算我的遞歸算法的最壞情況運行時復雜度。
目前,我選擇的基本操作是將兩個字符的索引進行比較,這是在if語句中進行的。 但是,此if語句是嵌套的,並且我不確定這如何影響遞歸算法中的t(n)。
我認為最壞情況下的運行時間復雜度是t(n) = N(N-1) = N^2 -1 or just O(n)=N^2?
我認為在最壞的情況下,將在外部if語句中檢查每個n個字符,這意味着在內部if語句中將對n-1個字符進行比較,從而得出了這種邏輯。
public class StringShuffleTest {
public static boolean isOrderedShuffle(String a, String b, String c){
//variables for the size of Strings a, b and c.
int n = a.length();
int m = b.length();
int len = c.length();
//if the length of c is not the length of a + b, return false.
if (len != (n + m)){
return false;
}
//if String c contains String b as a substring, then remove String b from c and make m = 0.
//This statement avoids errors when dealing with Strings with very similar characters.
if (c.contains(b)){
c = c.replace(b, "");
m = 0;
}
//if the length of a or b is 0, and c equals a or b, return true, otherwise,
//return false.
if (n == 0 || m == 0){
if (c.equals(a) || c.equals(b)){
return true;
}
else
return false;
}
//if String a has length 1, remove a from String c and make String a empty.
if (n == 1){
c = c.substring(0, c.indexOf(a.charAt(0))) + c.substring(c.indexOf(a.charAt(0)) +1);
a = "";
return isOrderedShuffle(a, b, c);
}
//An ordered shuffle of two given strings, a and b, is a string that can be formed by interspersing
//the characters of a and b in a way that maintains the left-to-right order of the characters from each
//string.
//Recursive algorithm to determine if String c is an ordered shuffle of a and b.
else
if (c.indexOf(a.charAt(0)) >= 0){
int indexOfFirsta = c.indexOf(a.charAt(0));
int indexOfSeconda = c.indexOf(a.charAt(1));
if (indexOfFirsta <= indexOfSeconda){
c = c.substring(0, indexOfFirsta) + c.substring(indexOfFirsta +1);
a = a.substring(1, n);
System.out.println(a);
System.out.println(c);
return isOrderedShuffle(a, b, c);
}
else
if (c.indexOf(b.charAt(0)) >= 0){
int indexOfFirstb = c.indexOf(b.charAt(0));
int indexOfSecondb = c.indexOf(b.charAt(1));
if (indexOfFirstb <= indexOfSecondb){
c = c.substring(0, indexOfFirstb) + c.substring(indexOfFirstb +1);
b = b.substring(1, m);
System.out.println(b);
System.out.println(c);
return isOrderedShuffle(a, b, c);
}
}
}
return false;
}
public static void main(String[] args) {
System.out.println(StringShuffleTest.isOrderedShuffle("abc", "def", "abedcf"));
}
}
如果您將時間復雜度分析分成幾部分,則將有幫助。
我們知道,每次調用isOrderedShuffle
,都會刪除至少一個字符。 現在,讓我們假設每次調用isOrderedShuffle
的復雜度為C。
T(n)= T(n-1)+ C
現在我們需要真正弄清楚C是什么。 為此,您想弄清楚函數中最復雜的操作是什么。 在這種情況下,我們可以看一下String的indexOf
函數。 當調用indexOf
一個字符作為參數,時間復雜度為O(n),其中n是我們正在尋找的字符串的長度(見這個答案,如果有興趣)。 在您的算法中,字符串為c。 因此,我們假設長度為n。 indexOf
被稱為固定次數。
C = O(n)
因此,
T(n)= T(n-1)+ n
我讓你把它簡化為封閉形式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.