Recursion & Backtracking · Pattern 6 of 9

Choice per position: menus and cuts

Fill the answer slot by slot, where each slot has its own menu of options: the letters of a digit, the next piece of a string, or the block that fits on top of two others.

4 variations · 9 problems · 1 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Each position of the input maps to a set of options
  • Split a string into valid pieces (palindromes, words, IP parts)
  • Build every number or string that follows a digit rule

The template

Choice per Position
// one menu per position: the letters on each phone key
String[] KEYS = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> letterCombinations(String digits) {
    List<String> out = new ArrayList<>();
    if (!digits.isEmpty()) letters(digits, 0, new StringBuilder(), out);
    return out;
}
void letters(String d, int i, StringBuilder sb, List<String> out) {
    if (i == d.length()) { out.add(sb.toString()); return; }
    for (char ch : KEYS[d.charAt(i) - '0'].toCharArray()) {
        sb.append(ch);
        letters(d, i + 1, sb, out);
        sb.deleteCharAt(sb.length() - 1);
    }
}

// choose where the next piece ends: every split into palindromes
List<List<String>> partition(String s) {
    List<List<String>> out = new ArrayList<>();
    cut(s, 0, new ArrayList<>(), out);
    return out;
}
void cut(String s, int start, List<String> path, List<List<String>> out) {
    if (start == s.length()) { out.add(new ArrayList<>(path)); return; }
    for (int end = start + 1; end <= s.length(); end++) {
        if (!isPal(s, start, end - 1)) continue;          // only valid pieces
        path.add(s.substring(start, end));
        cut(s, end, path, out);
        path.remove(path.size() - 1);
    }
}
boolean isPal(String s, int i, int j) {
    while (i < j) if (s.charAt(i++) != s.charAt(j--)) return false;
    return true;
}

The variations

  1. 1A fixed menu per position

    Each slot has its own short list of options: the letters of a key, the choices inside braces, or the digits that still read as a number upside down. Loop over the menu, recurse to the next slot. For mirrored numbers, fill from both ends at once.

  2. 2Cut the string into valid pieces

    The choice is where the next piece ends. Try every end, keep the piece only if it is valid (a palindrome, a dictionary word, a number from 0 to 255), and recurse on the rest.

  3. 3Build the next row block by block

    Each pair of neighbours in the current row has a menu of blocks that may sit on top. Choose one per pair to build the next row, then recurse on that row. Remembering rows that already failed keeps it fast.

  4. 4More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Returning [""] instead of [] for empty input in Letter Combinations.
  • Restore IP Addresses: forgetting that a part may not have a leading zero ("01") and must be at most 255.
  • Word Break II without a memo on the start index: the same suffix is solved again and again.
Next: Divide and conquer: split, solve, combine →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.