算法题LC46:distinct-subsequences

字符串,动态规划:
题目描述
给定一个字符串S和一个字符串T,计算S中的T的不同子序列的个数。
字符串的子序列是由原来的字符串删除一些字符(也可以不删除)在不改变相对位置的情况下的剩余字符(例如,"ACE"is a subsequence of"ABCDE"但是"AEC"不是)
例如:
S =“rabbbit”, T =“rabbit”
返回3

Given a string S and a string T, count the number of distinct subsequences of T in S.
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”
Return3.
输入描述

输出描述

示例1:
输入

输出
        
代码:

public class Solution {
     public int numDistinct(String S, String T) {
int length=T.length()+1;
int width=S.length()+1;
int[][]num=new int[length][width];
for(int i=0;i<length;i++)
    num[i][0]=0;
for(int n=0;n<width;n++)
    num[0][n]=1;
for(int j=1;j<length;j++)
    for(int m=1;m<width;m++)
    {
        if(S.charAt(m-1)==T.charAt(j-1))
        {num[j][m]=num[j][m-1]+num[j-1][m-1]; }
        else num[j][m]=num[j][m-1];
    }
 
return num[length-1][width-1];
    }
}

发布了80 篇原创文章 · 获赞 1 · 访问量 1405

猜你喜欢

转载自blog.csdn.net/alidingding/article/details/104673331