-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22-Generate_Parentheses.rs
More file actions
36 lines (31 loc) · 984 Bytes
/
Copy path22-Generate_Parentheses.rs
File metadata and controls
36 lines (31 loc) · 984 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
impl Solution {
pub fn generate_parenthesis(n: i32) -> Vec<String> {
let mut result = Vec::new();
let n = n as usize;
fn backtrack(
current: &mut String,
open: usize,
close: usize,
max: usize,
result: &mut Vec<String>,
) {
if open == max && close == max {
result.push(current.clone());
return;
}
if open < max {
current.push('(');
backtrack(current, open + 1, close, max, result);
current.pop();
}
if close < open {
current.push(')');
backtrack(current, open, close + 1, max, result);
current.pop();
}
}
let mut current = String::new();
backtrack(&mut current, 0, 0, n, &mut result);
result
}
}