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
- 45 lines of Java from the credited upstream file 1307.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 2 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 public boolean isSolvable(String[] words, String result) {3 rows = words.length + 1;4 for (final String word : words)5 cols = Math.max(cols, word.length());6 cols = Math.max(cols, result.length());7 return dfs(words, result, 0, 0, 0);8 }9 10 private Map<Character, Integer> letterToDigit = new HashMap<>();11 private boolean[] usedDigit = new boolean[10];12 private int rows = 0;13 private int cols = 0;14 15 private boolean dfs(String[] words, String result, int row, int col, int sum) {16 if (col == cols)17 return sum == 0;18 if (row == rows)19 return sum % 10 == 0 && dfs(words, result, 0, col + 1, sum / 10);20 21 String word = row == rows - 1 ? result : words[row];22 if (col >= word.length())23 return dfs(words, result, row + 1, col, sum);24 25 char letter = word.charAt(word.length() - col - 1);26 int sign = row == rows - 1 ? -1 : 1;27 28 if (letterToDigit.containsKey(letter) &&29 (letterToDigit.get(letter) > 0 || col < word.length() - 1))30 return dfs(words, result, row + 1, col, sum + sign * letterToDigit.get(letter));31 32 for (int digit = 0; digit < 10; ++digit)33 if (!usedDigit[digit] && (digit > 0 || col < word.length() - 1)) {34 letterToDigit.put(letter, digit);35 usedDigit[digit] = true;36 if (dfs(words, result, row + 1, col, sum + sign * letterToDigit.get(letter)))37 return true;38 usedDigit[digit] = false;39 letterToDigit.remove(letter);40 }41 42 return false;43 }44}45