2-D Dynamic Programming Two strings
562. Distinct Subsequences
You are given two strings, s and t. Count the ways to pick letters of s, keeping their order, so that
the picked letters spell t.
In other words, count the subsequences of s that are equal to t. A subsequence is what is left after
deleting some letters, or none, without changing the order of the rest. Two ways are different if they pick
a different set of positions in s, even when they spell the same string.
The count can be very large, so return it modulo 109 + 7. If t cannot be spelled at all, the
answer is 0.
Example 1
Input: s = "banana", t = "ana"
4Explanation: Counting positions from 0, the letters at (1, 2, 3), (1, 2, 5), (1, 4, 5) and (3, 4, 5) spell "ana".
Example 2
Input: s = "listen", t = "silent"
0Explanation: s has every letter of t, but in a different order. Both strings have six letters, so the only way
would be to pick all of s.
Example 3
Input: s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
t = "aaaaaaaaaaaaaaaaaaaa"
846527861Explanation: s has 40 letters and t has 20. Any 20 of the 40 letters spell t, which gives 137846528820 ways.
Modulo 109 + 7 that is 846527861.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ s.length ≤ 1041 ≤ t.length ≤ 1000sandthold only lowercase English letters.
Clarifying questions
What you would ask an interviewer before writing any code.