import java.util.*; public class BacktrackDemo { static void backtrack(List<Integer> nums, int start, List<Integer> path) { System.out.println(path); for (int i = start; i < nums.size(); i++) { path.add(nums.get(i)); backtrack(nums, i + 1, path); path.remove(path.size() - 1); } } public static void main(String[] args) { List<Integer> nums = Arrays.asList(1, 2); backtrack(nums, 0, new ArrayList<>()); } }
The code prints the current path at each recursive call before exploring further elements. It starts with an empty list, then adds 1, then adds 2, backtracks, and finally adds 2 alone.
For n elements, the decision tree has 2^n leaves and total nodes equal to 2^(n+1) - 1. For n=3, total nodes = 2^4 - 1 = 15.
import java.util.*; public class BacktrackBug { static void backtrack(List<Integer> nums, int start, List<Integer> path) { if (start == nums.size()) { System.out.println(path); return; } path.add(nums.get(start)); backtrack(nums, start + 1, path); path.remove(path.size() - 1); backtrack(nums, start + 1, path); } public static void main(String[] args) { List<Integer> nums = Arrays.asList(1, 2, 3); backtrack(nums, 0, new ArrayList<>()); } }
The code removes element at index 'start' from path, but path size changes during recursion. This causes IndexOutOfBoundsException when start is greater than path size.
import java.util.*; public class PermutationBacktrack { static void backtrack(List<Integer> nums, List<Integer> path, boolean[] used) { if (path.size() == nums.size()) { System.out.println(path); return; } for (int i = 0; i < nums.size(); i++) { if (used[i]) continue; used[i] = true; path.add(nums.get(i)); backtrack(nums, path, used); path.remove(path.size() - 1); used[i] = false; } } public static void main(String[] args) { List<Integer> nums = Arrays.asList(1, 2); backtrack(nums, new ArrayList<>(), new boolean[nums.size()]); } }
The code generates all permutations of [1, 2], which are [1, 2] and [2, 1].
Full search space is 2^(N^2) = 2^16 = 65536 nodes. Pruning halves branches at each of N=4 levels, so nodes ≈ 2^(N^2) / 2^N = 2^(16-4) = 2^12. But pruning at each queen placement level reduces more, approximated here as 2^(4).
