imashutosh51

Print all the LCS

May 9th, 2026
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.06 KB | None | 0 0
  1. #Print all LCS
  2. '''
  3. The Idea is very similar to the Printing the LCS but once you take a move, means taking the current character, you will move in diagonaly up like earlier.The only thing here is once left==up, means both are having different LCS so store both possibility.
  4.  
  5. Here each state brings one state only except the case when left==up which means left and up, both direction is having the LCS.so just store both in the q.
  6.  
  7. One more thing, consider that state visited if that state is removed from the q unlike the standard BFS.
  8. '''
  9.  
  10. from collections import deque
  11. def fun(n, m, text1, text2, dp):
  12.     if n < 0 or m < 0:
  13.         return 0
  14.     if dp[n][m] != -1:
  15.         return dp[n][m]
  16.     if text1[n] == text2[m]:
  17.         dp[n][m] = 1 + fun(n - 1, m - 1, text1, text2, dp)
  18.     else:
  19.         dp[n][m] = max(fun(n - 1, m, text1, text2, dp), fun(n, m - 1, text1, text2, dp))
  20.     return dp[n][m]
  21.  
  22. class Solution:
  23.     def allLCS(self, s1, s2):
  24.         n, m = len(s1), len(s2)
  25.         dp = [[-1] * m for _ in range(n)]
  26.         fun(n - 1, m - 1, s1, s2, dp)
  27.  
  28.         # Fix 1: Use collections.deque and Fix 2: add extra () for tuple
  29.         q = deque()
  30.         q.append((n-1,m-1,''))
  31.        
  32.         visited = set()
  33.         results = set()
  34.        
  35.         # Fix 3: Ensure variable name matches 'q'
  36.         while q:
  37.             i, j, current_ans = q.popleft()
  38.            
  39.             if i < 0 or j < 0:
  40.                 results.add(current_ans[::-1])
  41.                 continue
  42.            
  43.             if (i, j, current_ans) in visited:
  44.                 continue
  45.             visited.add((i, j, current_ans))
  46.  
  47.             if s1[i] == s2[j]:
  48.                 q.append((i - 1, j - 1, current_ans + s1[i]))
  49.             else:
  50.                 up = dp[i-1][j] if i > 0 else 0
  51.                 left = dp[i][j-1] if j > 0 else 0
  52.                
  53.                 if up >= left:
  54.                     q.append((i - 1, j, current_ans))
  55.                
  56.                 if left >= up:
  57.                     q.append((i, j - 1, current_ans))
  58.  
  59.         return sorted(list(results))
Advertisement
Add Comment
Please, Sign In to add comment