- 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
- 61 lines of Python from the credited upstream file minimum-window-subsequence.py.
- The implementation visibly relies on sequence storage, 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.
123 4class Solution(object):5 def minWindow(self, S, T):6 """7 :type S: str8 :type T: str9 :rtype: str10 """11 lookup = [[None for _ in xrange(26)] for _ in xrange(len(S)+1)]12 find_char_next_pos = [None]*2613 for i in reversed(xrange(len(S))):14 find_char_next_pos[ord(S[i])-ord('a')] = i+115 lookup[i] = list(find_char_next_pos)16 17 min_i, min_len = None, float("inf")18 for i in xrange(len(S)):19 if S[i] != T[0]:20 continue21 start = i22 for c in T:23 start = lookup[start][ord(c)-ord('a')]24 if start == None:25 break26 else:27 if start-i < min_len:28 min_i, min_len = i, start-i29 return S[min_i:min_i+min_len] if min_i is not None else ""30 31 323334class Solution2(object):35 def minWindow(self, S, T):36 """37 :type S: str38 :type T: str39 :rtype: str40 """41 dp = [[None for _ in xrange(len(S))] for _ in xrange(2)]42 for j, c in enumerate(S):43 if c == T[0]:44 dp[0][j] = j45 46 for i in xrange(1, len(T)):47 prev = None48 dp[i%2] = [None] * len(S)49 for j, c in enumerate(S):50 if prev is not None and c == T[i]:51 dp[i%2][j] = prev52 if dp[(i-1)%2][j] is not None:53 prev = dp[(i-1)%2][j]54 55 start, end = 0, len(S)56 for j, i in enumerate(dp[(len(T)-1)%2]):57 if i >= 0 and j-i < end-start:58 start, end = i, j59 return S[start:end+1] if end < len(S) else ""60 61