by pdwd » Sat Sep 18, 2010 3:08 am
This is my solution:
Let a - first string, b - second string, c - third string.
I have dp[k][i][j] - number of ways to make c[1..k] using letters from a[1..i] and b[1..j]
dp[0][i][j] = always 1 (there is only one way to make empty string - remove all letters from a and b)
dp[k][i][j] = dp[k][i-1][j] + dp[k][i][j-1] - dp[k][i-1][j-1] //I dont take letter a[i], then don't take b[j] and I have to subtract common part that I added twice
if(a[i] == c[k])
{
dp[k][i][j] += dp[k-1][i-1][j]; //I count all the ways to make c[1..k-1] and add the letter a[i] at the end of each one
dp[k][i][j] -= dp[k-1][i-1][j-1] //I already added dp[k][i][j-1], which includes ways in dp[k-1][i-1][j-1] and also dp[k-1][i-1][j] includes dp[k-1][i-1][j-1], so they were added twice
}
I do something similar in case b[j] == c[k]