Here is another spoj problem that asks how to find the number of distinct subsequences of a string ?
For example,
Input
AAA
ABCDEFG
CODECRAFTOutput
4
128
496
How can I solve this problem ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s a classic dynamic programming problem.
Let:
A null string has one subsequence, so
dp[0] = 1.Explanation
Initially, we assume we can append
a[i]to all subsequences ending on previous characters, but this might violate the condition that the counted subsequences need to be distinct. Remember thatlast[a[i]]gives us the last positiona[i]appeared on until now. The only subsequences we overcount are those that the previousa[i]was appended to, so we subtract those.Update these values as per their definition.
If your indexing starts from 0, use
a[i - 1]wherever I useda[i]. Also remember to wrap your computations in amodfunction if you’re going to submit code. This should be implemented like this:In order to correctly handle negative values in some languages (such as C/C++).