【发布时间】:2020-04-04 19:02:08
【问题描述】:
这是一个用于查找 X 和 Y 序列的所有最长公共序列的功能。 但是这个程序是用 c++ 编写的,但我想用 C 编写它。
有没有办法用数组代替集合?
例如。如果输入是
X = < A, A, T, C, C, >
Y = < A, C, A, C, G, >
那么输出应该是
< A, C, C, >
< A, A, C, >
m 和 n 分别是序列 X 和 Y 的大小。
/* source : https://www.geeksforgeeks.org/printing-longest-common-subsequence-set-2-printing/ */
/* Returns set containing all LCS for X[0..m-1], Y[0..n-1] */
set<string> findLCS(string X, string Y, int m, int n)
{
// construct a set to store possible LCS
set<string> s;
// If we reaches end of either string, return
// a empty set
if (m == 0 || n == 0)
{
s.insert("");
return s;
}
// If the last characters of X and Y are same
if (X[m - 1] == Y[n - 1])
{
// recurse for X[0..m-2] and Y[0..n-2] in
// the matrix
set<string> tmp = findLCS(X, Y, m - 1, n - 1);
// append current character to all possible LCS
// of substring X[0..m-2] and Y[0..n-2].
for (string str : tmp)
s.insert(str + X[m - 1]);
}
// If the last characters of X and Y are not same
else
{
// If LCS can be constructed from top side of
// the matrix, recurse for X[0..m-2] and Y[0..n-1]
if (L[m - 1][n] >= L[m][n - 1])
s = findLCS(X, Y, m - 1, n);
// If LCS can be constructed from left side of
// the matrix, recurse for X[0..m-1] and Y[0..n-2]
if (L[m][n - 1] >= L[m - 1][n])
{
set<string> tmp = findLCS(X, Y, m, n - 1);
// merge two sets if L[m-1][n] == L[m][n-1]
// Note s will be empty if L[m-1][n] != L[m][n-1]
s.insert(tmp.begin(), tmp.end());
}
}
return s;
}
【问题讨论】:
-
您可以为 C 编写自己的集合。AFAIK 集合是某种树。
-
@ThomasSablik 我很想 :( 谢谢。你能给我一个关于如何以数组形式执行插入的提示吗?
-
您真的需要一个集合还是可以使用 unordered_set?一个集合通常实现为red-black-tree。 unordered_set 通常被实现为某种哈希映射。
-
@ThomasSablik unordered 也很好,我认为。
-
创建一个包含
key和next的结构node。创建一个指向nodes 的指针数组。使用NULL初始化所有元素。创建一个哈希函数,该函数创建一个字符串的整数。数组中的元素是桶。每个桶都包含一个带有元素的链表。数组的大小就是桶的个数。