Approach
Depth-first search
For Verbal Arithmetic Puzzle, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 39 lines of Python from the credited upstream file 1307.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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 isSolvable(self, words: list[str], result: str) -> bool:3 words.append(result)4 rows = len(words)5 cols = max(map(len, words))6 letterToDigit = {}7 usedDigit = [False] * 108 9 def dfs(row: int, col: int, summ: int) -> bool:10 if col == cols:11 return summ == 012 if row == rows:13 return summ % 10 == 0 and dfs(0, col + 1, summ 10)14 15 word = words[row]16 if col >= len(word):17 return dfs(row + 1, col, summ)18 19 letter = word[~col]20 sign = -1 if row == rows - 1 else 121 22 if letter in letterToDigit and (23 letterToDigit[letter] > 0 or col < len(word) - 1):24 return dfs(row + 1, col, summ + sign * letterToDigit[letter])25 26 for digit, used in enumerate(usedDigit):27 if not used and (digit > 0 or col < len(word) - 1):28 letterToDigit[letter] = digit29 usedDigit[digit] = True30 if dfs(row + 1, col, summ + sign * digit):31 return True32 usedDigit[digit] = False33 if letter in letterToDigit:34 del letterToDigit[letter]35 36 return False37 38 return dfs(0, 0, 0)39