0

我们在秋季学期学习了动态规划理论,我正在努力复习并继续进一步研究它。我目前正在尝试一种天真的方法来解决此 TopCoder 文章中提到的 LCS 问题:动态编程

算法如下:

function LCS(S, T)
   if S is empty or T is empty then
      return empty string

   if first char of S == first char of T then
       return (first char of S) + LCS(S - first char, T - first char)

   otherwise // first chars are different
       return longer of LCS(S - first char, T) and LCS(S, T - first char)

例如,给定字符串“ABCDE”和“DACACBE”,最长的公共子序列是“ACE”。

但是,我的输出是有效的子字符串“ABE”而不是正确的“ACE”。我的实施顺序有什么问题?

#include <iostream>
#include <string>
using namespace std;


string LCS(string s, string t);

int main(){
  string A = "ABCDE";
  string B = "DACACBE";
  cout << LCS(A,B) << endl;
  return 0;
}

string LCS(string s, string t){

  string sSub = "";
  string tSub = "";
  if(!s.empty())
    sSub = s.substr(1);
  if(!t.empty())
    tSub = t.substr(1);

  if(s.empty() || t.empty()){
    return ""; // return an empty string if either are empty
  }

  if(s[0] == t[0]){
    string firstOfS = "";
    firstOfS += s[0];
    firstOfS += LCS(sSub, tSub);
    return s[0] + LCS(sSub, tSub);
  }

  else{
    string a = LCS(sSub, t);
    string b = LCS(s, tSub);
    if(a.length() > b.length()){
      return a;
    }
    else{
      return b;
    }
  }
}
4

1 回答 1

0

正如 Pham 所说,两者都是正确的,但是如果您想知道为什么是因为代码的最后一部分

  else{
    if(a.length() > b.length()){
      return a;
    }
    else{
      return b;
    }
  }   

如果 a.length() = b.length() 你总是返回 b。长度相同并不意味着它们相等。这就是为什么你有不同的答案但正确的答案:)

于 2015-12-23T03:34:14.980 回答