This is a 1-d DP. Set $dp[i]$ to be the decode ways for s[:i+1]
, we have:
$$ dp[i] = dp[i-2] \cdot M^{1}_{i} + dp[i-1] \cdot M^{2}_{i} $$
In which,
$$ \begin{aligned} M^{1}_{i} &= | \lbrace S[i] \in A^{1} \rbrace | \\ M^{2}_{i} &= | \lbrace S[i-1:i+1] \in A^{2} \rbrace \end{aligned} $$
- $M^{1}_{i}$ means how many ways to match the 1-character decoders $A^1$ with $S[i]$. In this problem we have either 1($S[i] \in A^{1}$) or 0(not match, or not exists)
- $M^{2}_{i}$ means how many ways to match the 2-character decoders $A^2$ with $S[i-1:i+1]$. In this problem we have either 1($S[i] \in A^{1}$) or 0(not match, or not exists)
|
|
Notes
- Use
get()
to take care of cases whens[i]
is not inone
- Take care of the corner cases when $i <= 2$, in which we can’t get dp values.
- Follow Up: Decode Ways 2