function backtrack(start: number, path: number[], result: number[][]) {
result.push([...path]);
for (let i = start; i < 2; i++) {
path.push(i + 1);
backtrack(i + 1, path, result);
path.pop();
}
}
const result: number[][] = [];
backtrack(0, [], result);
console.log(result);The function starts with an empty path and adds it to the result. Then it tries adding 1, recurses, then backtracks and tries adding 2. This generates all subsets including the empty set.
For permutations of 3 elements, the tree has 4 levels (including root). Number of nodes = 1 + 3 + 6 + 6 = 16. But the root is counted once, so total nodes are 1 + 3 + 6 + 6 = 16. However, the question includes root and leaves, so 16 is correct.
Rechecking: root (1), level 1 (3), level 2 (6), level 3 (6) total 16 nodes.
function backtrack(start: number, path: number[], result: number[][], sum: number) { if (path.length === 2) { result.push([...path]); return; } for (let i = start; i < 3; i++) { if (sum + i + 1 > 3) continue; path.push(i + 1); backtrack(i + 1, path, result, sum + i + 1); path.pop(); } } const result: number[][] = []; backtrack(0, [], result, 0); console.log(result);
The code only adds pairs where the sum is <= 3. The pairs are (1,2)=3, (1,3)=4, (2,3)=5. So only [1, 2] is included.
The 4-Queens problem has exactly 2 distinct solutions where no two queens attack each other.
The maximum depth equals the number of elements because each element is a decision point: include or exclude.