115. 不同的子序列

給定一個(gè)字符串 s 和一個(gè)字符串 t ,計(jì)算在 s 的子序列中 t 出現(xiàn)的個(gè)數(shù)。
字符串的一個(gè) 子序列 是指,通過刪除一些(也可以不刪除)字符且不干擾剩余字符相對(duì)位置所組成的新字符串。(例如,"ACE" 是 "ABCDE" 的一個(gè)子序列,而 "AEC" 不是)
題目數(shù)據(jù)保證答案符合 32 位帶符號(hào)整數(shù)范圍。
輸入:s = "rabbbit", t = "rabbit"
輸出:3
解釋:
如下圖所示, 有 3 種可以從 s 中得到 "rabbit" 的方案。
(上箭頭符號(hào) ^ 表示選取的字母)
rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^
采用DP,重點(diǎn)在于狀態(tài)轉(zhuǎn)移方程。令二維數(shù)組distinct_nums[][],distinct_nums[i][j]表示s[0...j]的子序列中t[0...i]出現(xiàn)的個(gè)數(shù)。我們可以這樣來填充distinct_nums[][]。如果s[j]不等于t[i],那子串不可能以s[j]結(jié)尾,故distinct_nums[i][j] = distinct_nums[i][j - 1]。如果s[j]等于t[i],那則有兩種情況,子串以s[j]結(jié)尾(distinct_nums[i - 1][j - 1])或者不以s[j]結(jié)尾(distinct_nums[i][j - 1])??偨Y(jié)下來:

distinct_nums[i][j] = distinct_nums[i - 1][j - 1] + distinct_nums[i][j - 1] if s[j] == t[i] else distinct_nums[i][j - 1]

時(shí)間空間復(fù)雜度均為O(s * t)

class Solution:
    def numDistinct(self, s: str, t: str) -> int:
        # cover the edge cases
        if t == '':
            return 1
        if s == '':
            return 0

        distinct_nums = list()
        for _ in range(len(t)):
            distinct_nums.append([0] * len(s))

        # initialise the first line
        for idx in range(len(s)):
            if s[idx] == t[0]:
                distinct_nums[0][idx] = (distinct_nums[0][idx - 1] + 1) if idx > 0 else 1
            else:
                distinct_nums[0][idx] = distinct_nums[0][idx - 1] if idx > 0 else 0

        # from left to right, top to down, fill the matrix
        for i in range(1, len(t)):
            for j in range(1, len(s)):
                distinct_nums[i][j] = distinct_nums[i][j - 1]
                if s[j] == t[i]:
                    distinct_nums[i][j] += distinct_nums[i - 1][j - 1]

        return distinct_nums[-1][-1]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容