- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 52 lines of Python from the credited upstream file 2060.py.
- The implementation visibly relies on cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def possiblyEquals(self, s1: str, s2: str) -> bool:3 def getNums(s: str) -> set[int]:4 nums = {int(s)}5 for i in range(1, len(s)):6 nums |= {x + y for x in getNums(s[:i]) for y in getNums(s[i:])}7 return nums8 9 def getNextLetterIndex(s: str, i: int) -> int:10 j = i11 while j < len(s) and s[j].isdigit():12 j += 113 return j14 15 @functools.lru_cache(None)16 def dp(i: int, j: int, paddingDiff: int) -> bool:17 """18 Returns True if s1[i..n) matches s2[j..n), accounting for the padding19 difference. Here, `paddingDiff` represents the signed padding. A positive20 `paddingDiff` indicates that s1 has an additional number of offset bytes21 compared to s2.22 """23 if i == len(s1) and j == len(s2):24 return paddingDiff == 025 26 if i < len(s1) and s1[i].isdigit():27 nextLetterIndex = getNextLetterIndex(s1, i)28 for num in getNums(s1[i:nextLetterIndex]):29 if dp(nextLetterIndex, j, paddingDiff + num):30 return True31 32 elif j < len(s2) and s2[j].isdigit():33 nextLetterIndex = getNextLetterIndex(s2, j)34 for num in getNums(s2[j:nextLetterIndex]):35 if dp(i, nextLetterIndex, paddingDiff - num):36 return True37 38 elif paddingDiff > 0:39 if j < len(s2):40 return dp(i, j + 1, paddingDiff - 1)41 42 elif paddingDiff < 0:43 if i < len(s1):44 return dp(i + 1, j, paddingDiff + 1)45 46 else: 47 if i < len(s1) and j < len(s2) and s1[i] == s2[j]:48 return dp(i + 1, j + 1, 0)49 return False50 51 return dp(0, 0, 0)52