Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Print all LCS
- '''
- 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.
- 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.
- One more thing, consider that state visited if that state is removed from the q unlike the standard BFS.
- '''
- from collections import deque
- def fun(n, m, text1, text2, dp):
- if n < 0 or m < 0:
- return 0
- if dp[n][m] != -1:
- return dp[n][m]
- if text1[n] == text2[m]:
- dp[n][m] = 1 + fun(n - 1, m - 1, text1, text2, dp)
- else:
- dp[n][m] = max(fun(n - 1, m, text1, text2, dp), fun(n, m - 1, text1, text2, dp))
- return dp[n][m]
- class Solution:
- def allLCS(self, s1, s2):
- n, m = len(s1), len(s2)
- dp = [[-1] * m for _ in range(n)]
- fun(n - 1, m - 1, s1, s2, dp)
- # Fix 1: Use collections.deque and Fix 2: add extra () for tuple
- q = deque()
- q.append((n-1,m-1,''))
- visited = set()
- results = set()
- # Fix 3: Ensure variable name matches 'q'
- while q:
- i, j, current_ans = q.popleft()
- if i < 0 or j < 0:
- results.add(current_ans[::-1])
- continue
- if (i, j, current_ans) in visited:
- continue
- visited.add((i, j, current_ans))
- if s1[i] == s2[j]:
- q.append((i - 1, j - 1, current_ans + s1[i]))
- else:
- up = dp[i-1][j] if i > 0 else 0
- left = dp[i][j-1] if j > 0 else 0
- if up >= left:
- q.append((i - 1, j, current_ans))
- if left >= up:
- q.append((i, j - 1, current_ans))
- return sorted(list(results))
Advertisement
Add Comment
Please, Sign In to add comment