- 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
- 44 lines of Python from the credited upstream file unique-paths-iii.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 uniquePathsIII(self, grid):6 """7 :type grid: List[List[int]]8 :rtype: int9 """10 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]11 12 def index(grid, r, c):13 return 1 << (r*len(grid[0])+c)14 15 def dp(grid, src, dst, todo, lookup):16 if src == dst:17 return int(todo == 0)18 key = (src, todo)19 if key in lookup:20 return lookup[key]21 22 result = 023 for d in directions:24 r, c = src[0]+d[0], src[1]+d[1]25 if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and \26 grid[r][c] % 2 == 0 and \27 todo & index(grid, r, c):28 result += dp(grid, (r, c), dst, todo ^ index(grid, r, c), lookup)29 30 lookup[key] = result31 return lookup[key]32 33 todo = 034 src, dst = None, None35 for r, row in enumerate(grid):36 for c, val in enumerate(row):37 if val % 2 == 0:38 todo |= index(grid, r, c)39 if val == 1:40 src = (r, c)41 elif val == 2:42 dst = (r, c)43 return dp(grid, src, dst, todo, {})44