Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 44 Wildcard Matching - State Design

Boolean 2D DP

Define dp[i][j]dp[i][j] = true if s[0..i1]s[0..i-1] matches p[0..j1]p[0..j-1].

Base cases: dp[0][0]=truedp[0][0] = true (empty matches empty), dp[0][j]=truedp[0][j] = true if p[0..j1]p[0..j-1] is all '*' (stars can match empty), and dp[i][0]=falsedp[i][0] = false for i>0i > 0 (non-empty string can't match empty pattern).

The '*' transition is the tricky part: it can match zero characters (dp[i][j1]dp[i][j-1]) or one-or-more characters (dp[i1][j]dp[i-1][j]).