• + 0 comments

    I was confused about the same thing, but apparently you only count common subsequences that begin with the first item of the second substring. This way there are no duplicates counted.

    ex.

    try your example: "abcdab"

    t=1: "a", "bcdab"

    you don't count anything because no common subsequence begins with 'b', the first char of the second substring.

    t=2: "ab", "cdab"
    you don't count anything because no common subsequence begins with 'c'

    t=3: "abc", "dab"
    you still don't count anything (same reason, now 'd')

    t=4: "abcd", "ab"
    "a" and "ab" begin with 'a', so there are 2 common subsequences we want

    t=5: "abcda", "b"
    "b" begins with 'b', so there is 1.

    total is 3, as expected.

    Programmaticaly, we only initialize the dp array for the first item of the second substring with all items of the first substring. (dp[0][n])

    Note that the solution reverses the two substrings (passes the second substring as the first) which is why it's not setting dp[n][0] instead.