CodingNodes / 2-D Dynamic Programming / Distinct Subsequences System design Space play · ←→ step · R restart

Problem

You are given two strings s and t.

A subsequence of s is what you get by deleting some letters of s (maybe none) and keeping the rest in their original order. Two subsequences count as different when they use different positions in s, even if they spell the same text.

Return how many different subsequences of s spell exactly t. The answer is guaranteed to fit in a 32-bit signed integer.

Constraints

  • 1 ≤ s.length, t.length ≤ 1000
  • both strings use English letters
  • the answer fits in a 32-bit signed integer

Examples: pick one to animate

Solutions

TimeO(m · n) SpaceO(m · n)

Time: The table has (m + 1) · (n + 1) cells and each one is filled from two neighbours in constant time.

Space: The full table of (m + 1) · (n + 1) counts is stored.

Let dp[i][j] be the number of ways the first i letters of s can spell the first j letters of t. The empty word has exactly one way, so the first column is 1. For each cell, the ways that skip s[i - 1] are dp[i - 1][j]. If s[i - 1] equals t[j - 1], we can also use it, which adds dp[i - 1][j - 1]. The counts can grow past 32 bits in the middle of the table, so wider integers are used.