标签:style blog color strong os for
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
.
题目的意思是从源字符串S中删除一些字符后的字符串与T相等的个数,如果熟悉《算法导论》的话,可以想到动态规划那一节关于由一个字符串通过增删变成另一个字符串解法
本题利用动态规划求解
设决策变量为path[i][j],表示S[1..i]的前i个字符通过删除字符变成T[1..j]的个数
那么状态转移方程为
path[i-1][j-1] (S[i] == T[j])
path[i][j] = path[i-1][j](删除S的第i个字符)+ (不删除字符)
0 (S[i] != T[j] )
class Solution { public: int numDistinct(string S, string T) { int n = S.length(), m=T.length(); if(n <= m) return S==T; vector<vector<int> > path(n+1,vector<int>(m+1,0)); for(int i = 0; i <=n ; ++ i) path[i][0] = 1; for(int j =1; j <= m; ++ j){ for(int i = 1; i <= n ; ++ i){ path[i][j] = path[i-1][j] + (S[i-1]==T[j-1] ? path[i-1][j-1] : 0); } } return path[n][m]; } };
Leetcode Distinct Subsequences,布布扣,bubuko.com
Leetcode Distinct Subsequences
标签:style blog color strong os for
原文地址:http://www.cnblogs.com/xiongqiangcs/p/3823309.html