def backtrack(path, choices, result):
if is_solution(path):
result.append(path[:]) # shallow copy
return
for choice in choices:
if is_valid(choice):
path.append(choice)
backtrack(path, choices, result)
path.pop() # undo
Permutations
def permute(nums):
result = []
def backtrack(path, remaining):
if not remaining:
result.append(path[:])
return
for i in range(len(remaining)):
path.append(remaining[i])
backtrack(path, remaining[:i] + remaining[i+1:])
path.pop()
backtrack([], nums)
return result
Generate Parentheses
// Java
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
backtrack(res, "", 0, 0, n);
return res;
}
void backtrack(List<String> res, String curr, int open, int close, int max) {
if (curr.length() == max * 2) { res.add(curr); return; }
if (open < max) backtrack(res, curr + "(", open+1, close, max);
if (close < open) backtrack(res, curr + ")", open, close+1, max);
}
More Problems
Problem
Pattern
Complexity
Combinations
Backtrack with start index
O(C(n,k))
N-Queens
Column + diagonal sets
O(n!)
Sudoku Solver
Row/col/box validation, backtrack
O(9ⁿ²)
Word Search
DFS + visited set
O(mn·4^L)
✏️ Exercise: Implement the general backtracking template. Solve Permutations and Generate Parentheses. Then attempt N-Queens on a 4×4 board.