NeverSayNever's blog

By NeverSayNever, 10 years ago, In English

I was solving a simple DP problem ..

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.

I made a recursive code which is like this ..

I initialise the DP array with -1 and used one based indexing in DP matrix ..

 int solve(string S,string T,int N,int M){
if( M <= 0)
        return 1 ;

    if( N <= 0 )
        return 0 ;

    int &ret = DP[N][M];
if(ret != -1)
    return ret ;
ret = 0 ;   
    if(S[N-1] == T[M-1]){
        ret += (solve(S,T,N-1,M-1)+solve(S,T,N-1,M)) ;
    }else{
        ret += (solve(S,T,N-1,M)) ;
    }

    ret ;

}

I was not getting correct answer then i changed my code and prepared a bottom up code which is this ..

int solve(string &S,string &T,int N,int M){

	
	for(int i=0;i<=N;i++)
		for(int j=0;j<=M;j++)
			DP[i][j] = 0;

	for(int i=0;i<=N;i++)
		DP[i][0] = 1;

	for(int i=1;i<=N;i++){
		for(int j=1;j<=M;j++){
			if(S[i-1] == T[j-1])
				DP[i][j] += DP[i-1][j-1] ;
			DP[i][j] += DP[i-1][j] ;
		}
	}
	return DP[N][M] ;
}

I got AC with this solution ..Essentially the same as previous one ..

I am still unable to find a bug in my previous code so can anyone help me please ..

Thanx in advance

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
10 years ago, # |
  Vote: I like it 0 Vote: I do not like it

What's with the last line of the solve function? I guess it should be "return ret;". Add -Wreturn-type (or -Wall if you want many other useful checks) to your compiler options and it shouldn't happen again.