fn backtrack(path: &mut Vec<i32>, nums: &[i32], index: usize) {
if index == nums.len() {
println!("{:?}", path);
return;
}
// Include nums[index]
path.push(nums[index]);
backtrack(path, nums, index + 1);
// Exclude nums[index]
path.pop();
backtrack(path, nums, index + 1);
}
fn main() {
let nums = vec![1, 2];
let mut path = Vec::new();
backtrack(&mut path, &nums, 0);
}The function explores all subsets by choosing to include or exclude each element in order. The order of printing is: include 1 then include 2, include 1 then exclude 2, exclude 1 then include 2, exclude 1 then exclude 2.
At each step, the algorithm branches into 2 choices, so total nodes are 2 multiplied by itself n times, which is 2^n.
The code swaps elements to generate permutations but forgets to swap them back after the recursive call. This causes the vector to remain changed, leading to duplicate or incorrect permutations.
The classic 4-Queens problem has exactly 2 distinct solutions where 4 queens can be placed on a 4x4 board without attacking each other.
Pruning cuts off branches that cannot lead to a solution early, so fewer nodes are explored. This can reduce the exponential time complexity significantly.
