Generate Balanced Parentheses Backtracking
Backtracking adds "(" while open is below n and ")" only when it would keep the prefix balanced, cloning each complete combination once.
Code
// 回溯 (backtracking):只有 open 未满才能加 '(',
// 只有 close 小于 open 才能加 ')',保证每个前缀始终 balanced
fn generate(n: usize) -> Vec<String> {
let mut out = Vec::new();
let mut current = String::new();
backtrack(n, 0, 0, &mut current, &mut out);
out
}
fn backtrack(n: usize, open: usize, close: usize, current: &mut String, out: &mut Vec<String>) {
if current.len() == 2 * n {
out.push(current.clone()); // 收集时克隆一份,回溯还要继续用原串
return;
}
if open < n {
current.push('(');
backtrack(n, open + 1, close, current, out);
current.pop(); // 撤销选择
}
if close < open {
current.push(')');
backtrack(n, open, close + 1, current, out);
current.pop();
}
}
fn main() {
for combo in generate(3) {
println!("{combo}");
}
}How it works
Everything happens inside the functions generate, backtrack and main.
The cycling part of this snippet is for combo in generate(3).
Points of care
- No dependency machinery at all — no registry file and no lockfile entry.
Putting it to use
The one signature that matters here is fn generate(n: usize) -> Vec<String>
Running the file executes main, which drives generate in order.
Core lines
fn generate(n: usize) -> Vec<String> {
let mut out = Vec::new();
let mut current = String::new();
backtrack(n, 0, 0, &mut current, &mut out);
out
}
Interactive Tools for This Topic
FAQ
- How do you run Generate Balanced Parentheses Backtracking?
- It runs as-is — treat the file as the whole program and execute it.
Report a problem with this exampleOpens a pre-filled issue on GitHub.