using System.Collections.Generic;
public static void Main()
string S1 = "SOLARSYSTEM";
string S2 = "EYSTSEOELEAR";
private static void FindLCS(string S1, string S2)
Console.Write("In {0} and {1} , LCS length is {2}", S1, S2, GetLCSLength(S1, S2));
HashSet<String> lcsSet = BackTrackAllLCS(S1, S2, S1.Length, S2.Length);
Console.Write("LCS Sequence ");
Console.WriteLine(string.Join(", ", lcsSet));
private static int GetLCSLength(string S1, string S2)
Board = new int[S1.Length + 1, S2.Length + 1];
for (int row = 0; row <= S1.Length; row++)
for (int column = 0; column <= S2.Length; column++)
if (row == 0 || column == 0)
else if (S1[row - 1] == S2[column - 1])
Board[row, column] = Board[row - 1, column - 1] + 1;
Board[row, column] = Math.Max(Board[row - 1, column], Board[row, column - 1]);
return Board[S1.Length, S2.Length];
private static HashSet<String> BackTrackAllLCS(string S1, string S2, int firstLen, int secondLen)
HashSet<String> lcsSet = new HashSet<String>();
if (firstLen == 0 || secondLen == 0)
if (S1[firstLen - 1] == S2[secondLen - 1])
HashSet<String> portions = BackTrackAllLCS(S1, S2, firstLen - 1, secondLen - 1);
foreach (String portion in portions)
lcsSet.Add(portion + S1[firstLen - 1]);
if (Board[firstLen - 1, secondLen] >= Board[firstLen, secondLen - 1])
lcsSet = BackTrackAllLCS(S1, S2, firstLen - 1, secondLen);
if (Board[firstLen, secondLen - 1] >= Board[firstLen - 1, secondLen])
HashSet<String> portions = BackTrackAllLCS(S1, S2, firstLen, secondLen - 1);
foreach (string portion in portions)