Complete the code to start the backtracking recursion with the initial empty path.
fn backtrack(path: &mut Vec<i32>, result: &mut Vec<Vec<i32>>) {
if path.len() == 3 {
result.push(path.clone());
return;
}
for num in 1..=3 {
path.push(num);
backtrack(path, result);
path.pop();
}
}
fn main() {
let mut result = Vec::new();
let mut path = Vec::new();
[1];
println!("{:?}", result);
}The backtracking function requires mutable references to both path and result to modify them during recursion. So we pass &mut path and &mut result.
Complete the code to check the base case when the path length reaches the target length.
fn backtrack(path: &mut Vec<i32>, result: &mut Vec<Vec<i32>>, target_len: usize) {
if path.len() [1] target_len {
result.push(path.clone());
return;
}
for num in 1..=3 {
path.push(num);
backtrack(path, result, target_len);
path.pop();
}
}The base case is when the current path length equals the target length, so we use == to check equality.
Fix the error in the recursive call to correctly pass the mutable references.
fn backtrack(path: &mut Vec<i32>, result: &mut Vec<Vec<i32>>, target_len: usize) {
if path.len() == target_len {
result.push(path.clone());
return;
}
for num in 1..=3 {
path.push(num);
backtrack([1], [2], target_len);
path.pop();
}
}Inside the backtracking function, path and result are already mutable references, so pass them directly in the recursive call.
Fill both blanks to create a decision tree that only includes paths where the sum is less than 5.
fn backtrack(path: &mut Vec<i32>, result: &mut Vec<Vec<i32>>, target_len: usize) {
if path.len() == target_len {
result.push(path.clone());
return;
}
for num in 1..=3 {
path.push(num);
if path.iter().copied().sum::<i32>() [1] 5 {
backtrack(path, result, target_len);
}
path.pop();
}
}We want to continue exploring only if the sum of the path is less than 5, so the condition uses <.
Fill all three blanks to create a backtracking function that builds combinations of length 2 from numbers 1 to 3 without repetition.
fn backtrack(start: i32, path: &mut Vec<i32>, result: &mut Vec<Vec<i32>>, target_len: usize) {
if path.len() == target_len {
result.push(path.clone());
return;
}
for num in [1]..=[2] {
path.push(num);
backtrack(num + 1, path, result, target_len);
path.pop();
}
}
fn main() {
let mut result = Vec::new();
let mut path = Vec::new();
backtrack([3], &mut path, &mut result, 2);
println!("{:?}", result);
}The loop runs from 1 to 3 inclusive, so blanks 1 and 2 are 1 and 3. The initial start value is 1.
