Skip to content

Commit 1077933

Browse files
committed
leetcode.com 115. Distinct Subsequences
문제 링크: https://leetcode.com/problems/distinct-subsequences/description/
1 parent 441876b commit 1077933

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def numDistinct(self, s: str, t: str) -> int:
6+
s = ' ' + s
7+
t = ' ' + t
8+
l_s = len(s)
9+
l_t = len(t)
10+
dp: List[List[int]] = [[[-1, 0] for _ in range(len(s))] for _ in range(len(t))]
11+
dp[0][0][0] = 0 # s의 0~c인덱스까지, t의 0~r인덱스까지 비교하여, match된 distinct subsequence 임을 뜻함
12+
dp[0][0][1] = 1 # s의 0~c인덱스까지, t의 0~r인덱스까지 비교하여, match된 distinct subsequence 의 개수
13+
14+
answer = 0
15+
16+
for r in range(1, l_t):
17+
for c in range(r, l_s - (l_t - r - 1)):
18+
if t[r] == s[c]:
19+
for b in range(r - 1, c):
20+
if dp[r - 1][b][0] == r - 1:
21+
dp[r][c][0] = r
22+
dp[r][c][1] += dp[r - 1][b][1]
23+
24+
if dp[r][c][0] == l_t - 1:
25+
answer += dp[r - 1][b][1]
26+
27+
return answer
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from unittest import TestCase
2+
from main import Solution
3+
4+
5+
class TestSolution(TestCase):
6+
def test1_num_distinct(self):
7+
sol = Solution()
8+
self.assertEqual(3, sol.numDistinct(s="rabbbit", t="rabbit"))
9+
10+
def test2_num_distinct(self):
11+
sol = Solution()
12+
self.assertEqual(5, sol.numDistinct(s="babgbag", t="bag"))

0 commit comments

Comments
 (0)