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

Distinct Subsequences

时间:2014-06-06 08:19:44      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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.

首先考虑动态规划,最初的想法是用矩阵grid[i][j]记录S[i]是否能与T[j]匹配,然后从右下角开始找,每步只能向左或者左上走,统计有多少条路可以到达左上角,但是发现会有问题,无法找到rabbbit这条路线(红色表示去掉的)。重新考虑状态方程,将grid[i][j]表示S(0,i)中T(0,j)出现的次数,首先,无论S[i]和T[j]是否相等,若不使用S[i],则grid[i][j] = grid[i-1][j];若S[i]==T[j],则可以使用S[i],则有grid[i][j] = grid[i-1][j]+grid[i-1][j-1]。这样使用了m*n的额外空间。由状态方程可以看出,第i行上的元素只与i-1行有关,则可以只记录本行和上一行的状态,之前的可以抛弃,这样,将空间复杂度降低到了O(n)。时间复杂度为O(m*n)。

代码如下:

bubuko.com,布布扣
 1 public int numDistinct(String S, String T) {
 2         int grid[] = new int[T.length()+1];
 3         grid[0] = 1;
 4         for (int i = 0; i < S.length(); ++i) {
 5             for (int j = T.length() - 1; j >= 0; --j) {
 6                 grid[j + 1] += S.charAt(i) == T.charAt(j) ? grid[j] : 0;
 7             }
 8         }
 9         return grid[T.length()];
10     }
bubuko.com,布布扣

bubuko.com,布布扣

Distinct Subsequences,布布扣,bubuko.com

Distinct Subsequences

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/apoptoxin/p/3767503.html

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