150強訪談中等

不同的子序列

“不同子序列”問題的詳細指南和 Python 實作。

問題陳述

中等

給定兩個字串 s 和 t,傳回 s 中等於 t 的不同子序列的數量。

字串的子序列是在不影響剩餘字元相對位置的情況下刪除原始字串中的一些(可以不是)字元而形成的新字串。 (即“ACE”是“ABCDE”的子序列,而“AEC”不是)。

寫一個函數 numDistinct(s: str, t: str) -> int

約束條件
  • 1 <= len(s), len(t) <= 1000
  • s and t consist of English letters

範例

Example 1
Input
s = "rabbbit", t = "rabbit"
Output
3
Explanation

There are 3 ways you can generate "rabbit" from s: **rab**b**bit**, **ra**b**bbit**, **rab**bb**it**.

Example 2
Input
s = "babgbag", t = "bag"
Output
5
Explanation

There are 5 ways you can generate "bag" from s.

Need a Hint?
考慮使用 2D DP 特定的資料結構,例如集合或堆疊。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。