[LeetCode]题解(python):115-Distinct Subsequences

题目来源:

  https://leetcode.com/problems/distinct-subsequences/


题意分析:

  给定字符串S和T,判断S中可以组成多少个T,T是S的子串。


题目思路:

  这是一个动态规划的问题。设定ans[i][j]为s[:i] 组成t[:j]的个数。那么动态规划方程为,if s[i - 1] == t[j - 1]: ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j];else: ans[i][j] = ans[i - 1][j]。


代码(python):

  

class Solution(object):
    def numDistinct(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: int
        """
        m,n = len(s),len(t)
        ans = [[0 for i in range(n+1)] for i in range(m+1)]
        for i in range(m + 1):
            ans[i][0] = 1
        for i in range(1,m + 1):
            for j in range(1,n + 1):
                if s[i - 1] == t[j - 1]:
                    ans[i][j] = ans[i - 1][j - 1] + ans[i - 1][j]
                else:
                    ans[i][j] = ans[i-1][j]
        return ans[m][n]
View Code
原文地址:https://www.cnblogs.com/chruny/p/5263808.html