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.
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
// 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;
} KEYS = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
def letter_combinations(digits): # one menu per position
out = []
def go(i, path):
if i == len(digits):
out.append(path)
return
for ch in KEYS[int(digits[i])]:
go(i + 1, path + ch) # a new string: nothing to undo
if digits:
go(0, "")
return out
def partition(s): # choose where the next piece ends
out, path = [], []
def cut(start):
if start == len(s):
out.append(path[:])
return
for end in range(start + 1, len(s) + 1):
piece = s[start:end]
if piece == piece[::-1]: # only valid pieces
path.append(piece); cut(end); path.pop()
cut(0)
return out // one menu per position: the letters on each phone key
const vector<string> KEYS = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
void letters(const string& d, int i, string& path, vector<string>& out) {
if (i == (int)d.size()) { out.push_back(path); return; }
for (char ch : KEYS[d[i] - '0']) {
path.push_back(ch);
letters(d, i + 1, path, out);
path.pop_back();
}
}
vector<string> letterCombinations(string digits) {
vector<string> out; string path;
if (!digits.empty()) letters(digits, 0, path, out);
return out;
}
// choose where the next piece ends: every split into palindromes
bool isPal(const string& s, int i, int j) {
while (i < j) if (s[i++] != s[j--]) return false;
return true;
}
void cut(const string& s, int start, vector<string>& path, vector<vector<string>>& out) {
if (start == (int)s.size()) { out.push_back(path); return; }
for (int end = start + 1; end <= (int)s.size(); end++) {
if (!isPal(s, start, end - 1)) continue; // only valid pieces
path.push_back(s.substr(start, end - start));
cut(s, end, path, out);
path.pop_back();
}
}
vector<vector<string>> partition(string s) {
vector<vector<string>> out; vector<string> path;
cut(s, 0, path, out);
return out;
} // one menu per position: the letters on each phone key
const KEYS = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
function letterCombinations(digits) {
const out = [];
function go(i, path) {
if (i === digits.length) { out.push(path); return; }
for (const ch of KEYS[digits.charCodeAt(i) - 48]) go(i + 1, path + ch); // nothing to undo
}
if (digits.length) go(0, "");
return out;
}
// choose where the next piece ends: every split into palindromes
function partition(s) {
const out = [], path = [];
const isPal = (i, j) => { while (i < j) if (s[i++] !== s[j--]) return false; return true; };
function cut(start) {
if (start === s.length) { out.push([...path]); return; }
for (let end = start + 1; end <= s.length; end++) {
if (!isPal(start, end - 1)) continue; // only valid pieces
path.push(s.slice(start, end)); cut(end); path.pop();
}
}
cut(0);
return out;
} The variations
-
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.
Now you solve -
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.
Now you solve -
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.
-
4More practice
More problems that use this pattern. Try them once the variations above feel easy.
Problems- Word Pattern II Medium Stuck? ▶ video
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.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.