Leetcode: 115. Distinct Subsequences (week12---hard)

115. Distinct Subsequences

题目

实例 

分析

题解


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).

实例 

 

分析

  • 可以看出这是一道动态规划的题目,而对于有两个字符串或对象之间的比较问题或者显式的二维问题一般开始步骤都是创建一个二维数组,数组的大小要为参数的长度加1,这是因为初始化的问题。
  • 所以这一道题也是一样,创建一个大小为N+1,M+1的数组,其中N是t(字串)的长度,M是s(母串)的长度。
  • 因为填表的顺序是从左至右,从上至下,也就是现在s[1:m]中匹配t[1:n]的串的个数,所以就数组的[0][:]赋值为1,而[:][1:]赋值为0
  • 填表的时候有以下的规则:
    • 当t[i] = s[j]的时候:
      • arr[i+1][j+1] = arr[i+1][j] + arr[i][j]
    • 反之则 arr[i+1][j+1] = arr[i+1][j]
  • 最后的返回值是arr[N][M]

题解

class Solution{
public:
    // s=>t the num of the ways to generate t
    int numDistinct(string s, string t) {
        int M = s.length();
        int N = t.length();
        int total[N+1][M+1];
        // means the a, b max
        for (int i = 0; i <= N; i++){
            total[i][0] = 0;
        }
        for (int i = 0; i <= M; i++){
            total[0][i] = 1;
        }
        for (int i = 0; i < N; i++){
            for (int j = 0; j < M; j++){
                total[i+1][j+1] = 0;
                if(t[i] == s[j]) total[i+1][j+1] = total[i + 1][j] +total[i][j];
                else total[i + 1][ j + 1] = total[i + 1][j];
            }
        }
        return total[N][M];
    }      
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值