首页 > 技术文章 > leetcode-115. Distinct Subsequences

hongyang 2017-02-22 13:47 原文

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"

Return 3.

 

思路:

经典的DP问题,用result[i][j]表示长度为i的S转换到长度为j的T的结果数。

s[i-1]==t[j-1]的时候result[i][j]=result[i-1][j-1]+result[i-1][j];

s[i-1]!=t[j-1]的时候result[i][j]=result[i-1][j];

 

Acceped Code:

 1 class Solution {
 2 public:
 3     int numDistinct(string s, string t) {
 4         if(s.empty()||t.empty())
 5         return 0;
 6         if(s.length()<t.length())
 7         return 0;
 8         int len1=s.length();
 9         int len2=t.length();
10         vector<vector<int>> result(len1+1,vector<int>(len2+1,0));
11         for(int i=0;i<=len1;i++)
12         result[i][0]=1;
13         for(int i=1;i<=len1;i++)
14         for(int j=1;j<=len2;j++)
15         {
16             result[i][j]=result[i-1][j];
17             if(s[i-1]==t[j-1])
18             result[i][j]+=result[i-1][j-1];
19         }
20         return result[len1][len2];
21     }
22 };

 

推荐阅读