码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 115. Distinct Subsequences

时间:2015-02-11 23:09:04      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:

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.

[Solution]

Let W(i, j) stand for the number of subsequences of S(0, i) in T(0, j). If S.charAt(i) == T.charAt(j), W(i, j) = W(i-1, j-1) + W(i-1,j); Otherwise, W(i, j) = W(i-1,j).

 1 int numDistinct(string S, string T) 
 2     {
 3         int m = S.size(), n = T.size(), i, j, result;
 4         int **table = new int* [m + 1];
 5         for (i = 0; i <= m; i++)
 6             table[i] = new int[n + 1];
 7         
 8         for (j = 0; j <= n; j++) // S is empty
 9             table[0][j] = 0;
10         for (i = 0; i <= m; i++) // T is empty
11             table[i][0] = 1;
12             
13         for (i = 1; i <= m; i++)
14         {
15             for (j = 1; j <= n; j++)
16             {
17                 if (S[i - 1] != T[j - 1])
18                     table[i][j] = table[i - 1][j];
19                 else
20                     table[i][j] = table[i - 1][j] + table[i - 1][j - 1];
21             }
22         }
23         result = table[m][n];
24         
25         for (i = 0; i <= m; i++)
26             delete[] table[i];
27         delete[] table;
28         
29         return result;
30     }

 

leetcode 115. Distinct Subsequences

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4287013.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!