Skip to content

Commit ac9f691

Browse files
committed
Add DP solution for Longest Common Subsequence
1 parent a8e5f12 commit ac9f691

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

โ€Žlongest-common-subsequence/KwonNayeon.py

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
- 1 <= text1.length, text2.length <= 1000
44
- text1 and text2 consist of only lowercase English characters.
55
6+
<Solution 1: DFS, ๋ฉ”๋ชจ์ด์ œ์ด์…˜ ํ™œ์šฉ>
7+
68
Time Complexity: O(m*n)
79
- m์€ text1์˜ ๊ธธ์ด, n์€ text2์˜ ๊ธธ์ด
810
- @cache๋กœ ์ค‘๋ณต ๊ณ„์‚ฐ์„ ๋ฐฉ์ง€ํ•˜์—ฌ ๊ฐ (i,j) ์กฐํ•ฉ์„ ํ•œ ๋ฒˆ๋งŒ ๊ณ„์‚ฐํ•จ
@@ -17,7 +19,6 @@
1719
- ๋‹ค๋ฅด๋ฉด: ํ•œ์ชฝ๋งŒ ์ด๋™ํ•œ ๊ฒฝ์šฐ ์ค‘ ์ตœ๋Œ“๊ฐ’ ์„ ํƒ
1820
3. base case: ์–ด๋А ํ•œ์ชฝ ๋ฌธ์ž์—ด ๋์— ๋„๋‹ฌํ•˜๋ฉด ์ข…๋ฃŒ
1921
"""
20-
2122
from functools import cache
2223
class Solution:
2324
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
@@ -32,3 +33,48 @@ def dfs(i, j):
3233
return max(dfs(i + 1, j), dfs(i, j + 1))
3334

3435
return dfs(0, 0)
36+
37+
"""
38+
<Solution 2: DP>
39+
40+
Time Complexity: O(n * m)
41+
- 2์ค‘ for๋ฌธ์œผ๋กœ ๋ชจ๋“  dp[i][j] ๊ณ„์‚ฐ
42+
43+
Space Complexity: O(n * m)
44+
- (n+1) * (m+1) ํฌ๊ธฐ์˜ DP ํ…Œ์ด๋ธ” ์‚ฌ์šฉ
45+
46+
ํ’€์ด๋ฐฉ๋ฒ•:
47+
- ์ƒํƒœ ์ •์˜: dp[i][j] = text1[:i]์™€ text2[:j]์˜ LCS ๊ธธ์ด
48+
- Subsequence: ์ˆœ์„œ๋งŒ ์œ ์ง€ํ•˜๋ฉด ๋จ
49+
- Substring: ์—ฐ์†์ ์œผ๋กœ ๋‚˜ํƒ€๋‚˜์•ผ ํ•จ
50+
51+
์ ํ™”์‹:
52+
- ๋ฌธ์ž๊ฐ€ ๊ฐ™์œผ๋ฉด: dp[i][j] = dp[i-1][j-1] + 1
53+
- ๋ฌธ์ž๊ฐ€ ๋‹ค๋ฅด๋ฉด: dp[i][j] = max(dp[i-1][j], dp[i][j-1])
54+
55+
ํ•ต์‹ฌ:
56+
- dp ํ…Œ์ด๋ธ” ํฌ๊ธฐ (n+1) * (m+1): ๋นˆ ๋ฌธ์ž์—ด ์ผ€์ด์Šค ํฌํ•จ
57+
- ์ตœ์ข… ๋‹ต: dp[n][m] (์ „์ฒด ๋ฌธ์ž์—ด ๋น„๊ต ๊ฒฐ๊ณผ)
58+
59+
๋…ธํŠธ:
60+
- DP ํŒจํ„ด์„ ์ฐพ์•„๋‚ด๋Š” ์—ฐ์Šตํ•˜๊ธฐ
61+
- ๋งคํŠธ๋ฆญ์Šค ํ™œ์šฉ
62+
"""
63+
class Solution:
64+
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
65+
n, m = len(text1), len(text2)
66+
67+
# DP ํ…Œ์ด๋ธ” ์ดˆ๊ธฐํ™”
68+
dp = [[0] * (m + 1) for _ in range(n + 1)]
69+
70+
# DP ํ…Œ์ด๋ธ” ์ฑ„์šฐ๊ธฐ
71+
for i in range(1, n + 1):
72+
for j in range(1, m + 1):
73+
if text1[i-1] == text2[j-1]:
74+
# ๋ฌธ์ž๊ฐ€ ๊ฐ™์œผ๋ฉด: ๋‘˜ ๋‹ค ์„ ํƒ + ์ด์ „ ๊ฒฐ๊ณผ
75+
dp[i][j] = 1 + dp[i-1][j-1]
76+
else:
77+
# ๋ฌธ์ž๊ฐ€ ๋‹ค๋ฅด๋ฉด: ๋‘˜ ์ค‘ ํ•˜๋‚˜ ์ œ์™ธํ•˜๊ณ  ์ตœ๋Œ€๊ฐ’
78+
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
79+
80+
return dp[n][m]

0 commit comments

Comments
ย (0)