https://leetcode.com/problems/longest-common-subsequence/
알고리즘의 전형적인 LCA문제 그 자체이다.
이 문제는 top-down 방식과 bottom-up 방식 두 가지로 풀어보았다.
<top-down>
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
memo = {}
n, m = len(text1), len(text2)
def top_down(i, j):
if (i, j) in memo:
return memo[(i, j)]
if i>=n or j>=m:
return 0
if text1[i] == text2[j]:
return top_down(i+1, j+1) + 1
memo[(i, j)] = max(top_down(i, j+1), top_down(i+1, j))
return memo[(i, j)]
return top_down(0, 0)
<bottom-up>
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
n, m = len(text1), len(text2)
dp = [[0]*(m+1) for _ in range(n+1)]
for i in range(n):
for j in range(m):
if text1[i] == text2[j]:
dp[i+1][j+1] = dp[i][j] + 1
else:
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])
return dp[-1][-1]
'알고리즘' 카테고리의 다른 글
[프로그래머스] 2 x n 타일링 문제 풀이와 코드 (0) | 2023.01.10 |
---|---|
LeetCode 2258. Escape the Spreading Fire (BFS, Dijkstra) (0) | 2022.06.22 |
LeetCode BFS문제: 909. Snakes and Ladders (0) | 2022.05.31 |
LeetCode 다익스트라 알고리즘, DFS 문제: 778. Swim in Rising Water (0) | 2022.05.26 |
LeetCode DFS문제: 1202. Smallest String With Swaps(Sorting, DFS, 자바스크립트 이중배열) (0) | 2022.05.25 |