[英]longest common subsequence using memoization
This program is of longest common subsequence using memoization. 该程序是使用备忘录的最长公共子序列。 But it is giving answer 0 for the below example.
但是下面的示例给出的答案为0。 Before adding memoization, it was giving correct answer 2.
在添加备忘录之前,它给出了正确的答案2。
I think I did mistake in adding memoization. 我认为在添加备注方面确实犯了错误。 Can anyone help me with what is wrong with this code?
谁能帮我解决这段代码有什么问题吗?
#include<bits/stdc++.h>
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
char a[100]="bd",b[100]="abcd";
int lcs1[100][100];
int lcs(int i,int j){
int temp;
if(lcs1[i][j]!=-1)
if(a[i]=='\0'||b[i]=='\0'){
return 0;
}
if(lcs1[i][j]!=-1)
return lcs1[i][j];
else if (a[i]==b[j])
temp = 1+lcs(i+1,j+1);
else
temp = max(lcs(i+1,j),lcs(i,j+1));
lcs1[i][j] = temp;
return temp;
}
int main(){
int temp = lcs(0,0);
memset(lcs1,-1,sizeof(lcs1));
printf("%d",temp);
}
2 problems: 2个问题:
lcs()
lcs()
之后初始化了记忆数组 if
in the beginning of your lcs()
if
您在lcs()
的开头有额外的lcs()
Here is corrected code: 这是更正的代码:
#include<cstring>
#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
char a[100]="bd",b[100]="abcd";
int lcs1[100][100];
int lcs(int i,int j){
int temp;
//if(lcs1[i][j]!=-1) // problem 2
if(a[i]=='\0'||b[i]=='\0'){
return 0;
}
if(lcs1[i][j]!=-1)
return lcs1[i][j];
else if (a[i]==b[j])
temp = 1+lcs(i+1,j+1);
else
temp = max(lcs(i+1,j),lcs(i,j+1));
lcs1[i][j] = temp;
return temp;
}
int main(){
memset(lcs1,-1,sizeof(lcs1)); // problem 1
int temp = lcs(0,0);
printf("%d",temp);
}
Note: that it is a good practice to avoid global variables. 注意:避免全局变量是一个好习惯。 Try to capsulate them in structures or classes.
尝试将它们封装在结构或类中。 See @Matthieu Brucher's answer for proper C++ implementation.
有关正确的C ++实现,请参见@Matthieu Brucher的答案。
Just for fun, a C++17 implementation with classes: 只是为了好玩,一个带有类的C ++ 17实现:
#include <iostream>
#include <vector>
#include <string_view>
class LCSMemoizer
{
std::vector<std::vector<int>> memory;
std::string_view s1;
std::string_view s2;
public:
LCSMemoizer(std::string_view s1, std::string_view s2)
: memory(s1.size(), std::vector<int>(s2.size(), -1)), s1(s1), s2(s2)
{
}
int run(unsigned int i1, unsigned int i2)
{
if(i1 == s1.size() || i2 == s2.size())
{
return 0;
}
if(memory[i1][i2] != -1)
{
return memory[i1][i2];
}
int sub = 0;
if(s1[i1] == s2[i2])
{
sub = run(i1+1, i2+1);
sub += 1;
}
else
{
sub = std::max(run(i1, i2+1), run(i1+1, i2));
}
memory[i1][i2] = sub;
return sub;
}
};
int lcs(std::string_view s1, std::string_view s2)
{
LCSMemoizer m(s1, s2);
return m.run(0, 0);
}
int main()
{
std::cout << lcs("bd", "abcd");
}
Also note that the usual question is not just to return the count, but also the string itself. 还要注意,通常的问题不仅是返回计数,还包括字符串本身。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.