Leetcode:Distinct Subsequences

来源:互联网 发布:软件企业每年认定 编辑:程序博客网 时间:2024/06/05 16:03

url:

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

描述:

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.

解题思路

动态规划
dp(i,j) 表示S(0,i) 子串和T(0,j)字串的“count the number of distinct subsequences”。则有以下公式
1. s[i] == t[j]时,dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
2. s[i]!=t[j]时,dp[i][j]=dp[i-1][j]
以下给出代码:

class Solution {    public int numDistinct(String s, String t) {            int[][]dp = new int[s.length()+1][t.length()+1];            //初始化,当t为空时,是s(0,i)[0<=i<=s.size]的子串。            for(int i=0;i<=s.length();i++)                dp[i][0] = 1;            for(int i=1;i<=t.length();i++){                for(int j=i;j<=s.length();j++){                    if(s.charAt(j-1)!=t.charAt(i-1)){                        dp[j][i] = dp[j-1][i];                    }else{                        dp[j][i] = dp[j-1][i-1]+dp[j-1][i];                    }                }            }            return dp[s.length()][t.length()];        }}
原创粉丝点击