In my personal opinion, this stupid problem is harder than an ordinary DP, because:
- state transition is weird(multiplication…)
- we need another data structure to pre-compute something
Idea
We need to match chars in word and chars in target, but with the given restriction.
- once we take a char in word, the char and the char to the left from all words are not available anymore
- we can start from any word, not necessarily from the first word
- target can be shorter than words[0]
Base Case
Success case: chars in targets are all matched(m>=len(target)
). We return 1 as this is one solution.
Fail case: (1)words are used up and (2)some chars left unmatched in target. i>=len(words[0])
, we reply on the success case check to handle (2).
DP States
word pointer(i)
Since we need to know what chars are available, we need to know what we have taken, so the index of word that we have already taken has to be one of the states.
target pointer(m)
This is straight forward, we need to know until which index, we have matched the chars.
Why we don’t need a pointer to record which word in words list we have used?
This is because we can start from any word.
State Transition
This is the hard part.
Let’s say we have dp(i,m)
We need to know how many word[i]
is equal to target[m]
so that we can match this pair of chars.
Assume there are x
matches, then we have 2 options:
x==0
- in this case, we have NO match, thus we have to proceed to
i+1
without doing anything - so the transition is
result=dp(i+1,m)
- in this case, we have NO match, thus we have to proceed to
x>0
- we have
x
matches and all these matches can combine with the next available matches(dp(i+1,m+1)
), so we need to multiply them to get in how many ways we can match them. - so the transition is
result=x*dp(i+1,m+1)
- we have
Algorithm
We have DP states, transitions, usually we can code the solution at this point but we have one more thing to settle, how do we calculate x
(how many word[i]
is equal to target[m]
so that we can match this pair of chars)?
We need to do a pre-processing, to calculate the lower case english letters count at each i
|
|
Now we’re ready to go!
|
|