當我試圖記憶最長公共子序列問題的遞歸解決方案時,memoized soln返回不同的答案。我不能完全似乎弄清楚爲什麼...記憶最長公共子序列算法的遞歸解決方案
#include <iostream>
#include <map>
#include <string>
#include <utility>
using namespace std;
string char_to_string(char c) { return string(1, c); }
map< pair<string, string>, string > hash;
// CORRECTED ANSWER AS PER DUKE'S SOLUTION - THANKS!
string lcsRec(string s1, string s2, string lcs = "") {
pair<string, string> s1s2 = make_pair(s1, s2);
pair< pair<string, string>, string> lcsTriplet = make_pair(s1s2, lcs);
if (hash.count(lcsTriplet)) {
return hash[lcsTriplet];
}
if (s1.size() == 0 || s2.size() == 0)
return hash[lcsTriplet] = lcs;
string s1Minus1 = s1.substr(0, s1.size() - 1);
string s2Minus1 = s2.substr(0, s2.size() - 1);
if (s1[s1.size() - 1] == s2[s2.size() - 1])
return hash[lcsTriplet] = lcsRec(s1Minus1, s2Minus1, char_to_string(s1[s1.size() - 1]) + lcs);
string omits1 = lcsRec(s1Minus1, s2, lcs);
string omits2 = lcsRec(s1, s2Minus1, lcs);
return hash[lcsTriplet] = (omits1.size() > omits2.size()) ? omits1 : omits2;
}
// MEMOIZED SOLUTION
string lcsRec(string s1, string s2, string lcs = "") {
pair<string, string> p0 = make_pair(s1, s2);
if (hash.count(p0)) return hash[p0];
if (s1.size() == 0 || s2.size() == 0)
return hash[p0] = lcs;
string s1Minus1 = s1.substr(0, s1.size() - 1);
string s2Minus1 = s2.substr(0, s2.size() - 1);
if (s1[s1.size() - 1] == s2[s2.size() - 1])
return hash[p0] = lcsRec(s1Minus1, s2Minus1, char_to_string(s1[s1.size() - 1]) + lcs);
string omits1 = lcsRec(s1Minus1, s2, lcs);
string omits2 = lcsRec(s1, s2Minus1, lcs);
return hash[p0] = (omits1.size() > omits2.size()) ? omits1 : omits2;
}
// NON-MEMOIZED SOLUTION
string lcsRec(string s1, string s2, string lcs = "") {
if (s1.size() == 0 || s2.size() == 0)
return lcs;
string s1Minus1 = s1.substr(0, s1.size() - 1);
string s2Minus1 = s2.substr(0, s2.size() - 1);
if (s1[s1.size() - 1] == s2[s2.size() - 1])
return lcsRec(s1Minus1, s2Minus1, char_to_string(s1[s1.size() - 1]) + lcs);
string omits1 = lcsRec(s1Minus1, s2, lcs);
string omits2 = lcsRec(s1, s2Minus1, lcs);
return (omits1.size() > omits2.size()) ? omits1 : omits2;
}
int main() {
// cout << lcsRec("ooappleoot", "motot") << endl;
// hash.clear();
// cout << lcsRec("hello", "hello") << endl;
// hash.clear();
cout << lcsRec("hhelloehellollohello", "hellohellok") << endl;
// for(map< pair<string, string>, string >::iterator iter = hash.begin(); iter != hash.end(); ++iter) {
// cout << iter->first.first << " " << iter->first.second << " " << iter->second << endl;
// }
}
有時。 (s1,s2)相同。我想,它會取代舊的。 – MarshalSHI