首頁  >  文章  >  後端開發  >  C程式中LCS的空間最佳化解決方案?

C程式中LCS的空間最佳化解決方案?

王林
王林轉載
2023-09-05 13:45:06834瀏覽

C程式中LCS的空間最佳化解決方案?

在這裡,我們將看到一種針對 LCS 問題的空間最佳化方法。 LCS是最長公共子序列。如果兩個字串是“BHHUBC”和“HYUYBZC”,那麼子序列的長度是4。動態規劃方法已經是它們的一種,但是使用動態規劃方法,會佔用更多的空間。我們需要 m x n 階的表,其中 m 是第一個字串中的字元數,n 是第二個字串中的字元數。

這裡我們將了解如何使用 O(n ) 輔助空間量。如果我們觀察舊方法,我們可以在每次迭代中看到,我們需要前一行的資料。並非所有數據都是必需的。所以如果我們做一個大小為2n的表,那就沒問題了。讓我們看看演算法來理解這個想法。

演算法

lcs_problem(X, Y) -

begin
   m := length of X
   n := length of Y
   define table of size L[2, n+1]
   index is to point 0th or 1st row of the table L.
   for i in range 1 to m, do
      index := index AND 1
      for j in range 0 to n, do
         if i = 0 or j = 0, then
            L[index, j] := 0
         else if X[i - 1] = Y[j - 1], then
            L[index, j] := L[1 – index, j - 1] + 1
         else
            L[index, j] := max of L[1 – index, j] and L[index, j-1]
         end if
      done
   done
   return L[index, n]
end

範例

#include <iostream>
using namespace std;
int lcsOptimized(string &X, string &Y) {
   int m = X.length(), n = Y.length();
   int L[2][n + 1];
   bool index;
   for (int i = 0; i <= m; i++) {
      index = i & 1;
      for (int j = 0; j <= n; j++) {
         if (i == 0 || j == 0)
            L[index][j] = 0;
         else if (X[i-1] == Y[j-1])
            L[index][j] = L[1 - index][j - 1] + 1;
         else
            L[index][j] = max(L[1 - index][j], L[index][j - 1]);
      }
   }
   return L[index][n];
}
int main() {
   string X = "BHHUBC";
   string Y = "HYUYBZC";
   cout << "Length of LCS is :" << lcsOptimized(X, Y);
}

輸出

Length of LCS is :4

以上是C程式中LCS的空間最佳化解決方案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除