zoukankan      html  css  js  c++  java
  • Leetcode -- 115. Distinct Subsequences

    Given a string S and a string T, count the number of distinct subsequences of S which equals T.

    A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

    Here is an example:
    S = "rabbbit", T = "rabbit"

    Return 3.

    class Solution(object):
        def numDistinct(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: int
            """
            # 关键是定义各个状态,找出状态转移方程
            # dp[i][j]表示字符串s[0~i-1] 中有多少个t[0~j-1].
            dp = [[0 for col in range(len(t) + 1)] for row in range(len(s) + 1)]
            if len(t) == 0 or len(s) == 0:
                return 0
            for i in range(len(s) + 1):     # 给第一列边界值赋值,此时为s[0],即为空时
                dp[i][0] = 1
            for i in range(1,len(s) + 1):
                for j in range(1, len(t) + 1):
                    if s[i - 1] == t[j - 1]:  # 因为比dp的维度要小1,所以为i-1,j-1
                        #如果S的第i个字符和T的第j个字符相同,那么所有dp[i-1][j-1]中满足的结果都会成为新的满足的序列
                        dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j]
                    else:
                        #假设S的第i个字符和T的第j个字符不相同,那么就意味着dp[i][j]的值跟res[i-1][j]是一样
                        dp[i][j] = dp[i - 1][j]
            return dp[len(s)][len(t)]
                
            
            
  • 相关阅读:
    java中==和equels的区别
    synchronized的用法及原理
    分库分表之Mycat实现
    Mysql架构和索引及性能优化
    Java内存模型与反向代理服务器Nginx
    Spring基础知识
    使用和理解线程池
    知识补充(数据库优化、三大范式)
    最大子数组问题,分治法求解
    Mybatis学习笔记
  • 原文地址:https://www.cnblogs.com/simplepaul/p/7290905.html
Copyright © 2011-2022 走看看