Big O用于以下递归解决方案

时间:2018-02-11 02:26:59

标签: c++ algorithm recursion big-o

我编写了以下代码,用于查找两个字符串之间的最小删除距离

enter code here
#include <iostream>
#include <string>

using namespace std;
int  DeletionDistance(const string& str1, const string& str2, int len1, int  
len2){
int index1=0;
int index2=0;
int count=0;
int str1len=str1.length();
int str2len=str2.length();
//calculate the base case if a string is empty, the deletion distance is the 
length of the other string
//since we need to delete all the other chars from the non empty string in 
order to match the two strings
if(str1len<=0)
  return str2len;
else if(str2len<=0)
  return str1len;
else{
//the strings are non empty. Recursively calculate the min del distance 
  if(str1[index1]==str2[index2]){
     //the chars match , hence the deletion distance would depend on the 
       remaining chars in both strings
      return DeletionDistance(str1.substr(index1+1,len1), 
                              str2.substr(index2+1,len2), len1, len2);  
  }
  else
    //the chars dont match 
    return (1+min(DeletionDistance(str1.substr(index1+1,len1), 
                                   str2.substr(index2,len2), len1, len2),
                  DeletionDistance(str1.substr(index1,len1), 
                                   str2.substr(index2+1,len2), len1, 
                                   len2)));
    }
}

 int deletionDistance( const string& str1, const string& str2 ) 
 {
  int len1 = str1.length();
  int len2 = str2.length();
  return DeletionDistance(str1, str2, len1, len2);

 }

在这段代码中,我们递归计算两个字符串之间的最小删除距离,如何计算时间和空间的复杂度? 我被告知这个解决方案的时间和空间复杂度是O(ab)其中,  a =字符串1的len  b =字符串2的len 我真的很感激有关如何开始为这样的递归解决方案开始计算Big O的一些解释或指示。 我能够计算bigO用于更简单的递归解决方案,如Fibonacci系列,阶乘等,但这比我好。

1 个答案:

答案 0 :(得分:1)

代码的复杂性为 O(2 ^ (| A | + | B |),其中 | A | | B | 分别是第一个和第二个字符串的大小。

这样做的原因是,在最坏的情况下,当递归到达两个字符串中的最后一个字符时,您的递归将返回。在你的代码中,每次你在第一个或第二个字符串中前进一步。所以一般来说,你的递归深度为(| A | + | B |),你的代码包含 2 递归调用。

如评论中所述,您可以使用动态编程实现 O(| A | * | B |)的复杂性。这是一个很好的tutorial,它将引导您完成它。您的问题接近最长公共子序列问题(LCS)。