LeetCode: 115. Distinct Subsequences

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.

题目大意: 给定 S 串和 T 串,求出 S 串中有多少个子序列等于 T 串。

解题思路 —— 动态规划

  • 记:distinctSeqNum[i][j] 为 S 串的前 i 个字符的子串中等于 T 的前 j 个字符的情况数
  • 初始化: distinctSeqNum[0...n][0] = 1(S 串总是能生成空序列), distinctSeqNum[0][1...n] = 0(空串总是无法 T 串序列)。
  • 如果 S[i] != T[j], 那么 S 串的前 i 个字符的子串中等于 T 的前 j 个字符的情况数就和S串不要第 i 个字符的情况一样。 即, distinctSeqNum[i][j] = distinctSeqNum[i-1][j]
  • 如果 S[i] == T[j], 那么生成 T 的子序列不要 S 的第 i 个字符,则distinctSeqNum[i][j] = distinctSeqNum[i-1][j]。 如果生成 T 的子序列要 S 的第 i 个字符,则,distinctSeqNum[i][j] = distinctSeqNum[i-1][j-1]。综上,distinctSeqNum[i][j] = distinctSeqNum[i-1][j] + distinctSeqNum[i-1][j-1]

AC 代码

class Solution {
public:
    int numDistinct(string s, string t) {
        //  distinctSeqNum[i][j]: s 串的前 i 个字符的子串中等于 t 的前j个字符的情况数
        vector<vector<int>> distinctSeqNum; 

        // initializing...
        distinctSeqNum.resize(s.size()+1, vector<int>(t.size()+1, 0));
        for(int i = 0; i <= s.size(); ++i)
        {
            distinctSeqNum[i][0] = 1;
        }

        for(size_t i = 0; i < s.size(); ++i)
        {
            for(size_t j = 0; j < t.size(); ++j)
            {
                if(j > i) break;

                if(s[i] == t[j]) 
                {
                    distinctSeqNum[i+1][j+1] = distinctSeqNum[i][j] + distinctSeqNum[i][j+1];
                }
                else
                {
                    distinctSeqNum[i+1][j+1] = distinctSeqNum[i][j+1];
                }
            }
        }

        return distinctSeqNum[s.size()][t.size()];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值