function backtrack(start, path) {
if (start === 2) {
console.log(path.join('->') || 'empty');
return;
}
backtrack(start + 1, path);
backtrack(start + 1, [...path, start + 1]);
}
backtrack(0, []);The function explores subsets by either skipping or including the next number. The base case prints the current path or 'empty' if none.
Order of prints is: empty (no elements), then subset with 2, then subset with 1, then subset with 1 and 2.
At each step, the tree branches into 2 choices, so total nodes are sum of 2^0 + 2^1 + ... + 2^(n-1) = 2^n - 1.
function backtrack(start, path, sum) { if (sum > 3) return; if (sum === 3) { console.log(path.join('->')); return; } for (let i = start; i < 3; i++) { backtrack(i + 1, [...path, i + 1], sum + i + 1); } } backtrack(0, [], 0);
The code prints subsets whose sum is exactly 3. The subsets are [1,2] and [3].
function backtrack(start, path, sum) { if (sum === 3) { console.log(path.join('->')); return true; } if (sum > 3) return false; for (let i = start; i < 3; i++) { if (backtrack(i + 1, [...path, i + 1], sum + i + 1)) return true; } return false; } backtrack(0, [], 0);
The first subset found with sum 3 is [1,2], so it prints '1->2' and stops.
From top-left to bottom-right in a 2x2 grid, you must move 2 rights and 2 downs in any order. Number of unique paths is combinations of 4 moves taken 2 at a time: C(4,2) = 6.
But since grid is 2x2 (3 rows and 3 columns points), actually moves needed are 2 rights and 2 downs, so total paths = 6.
