-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_parentheses.rs
55 lines (46 loc) · 1.25 KB
/
generate_parentheses.rs
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
///
/// Problem: Generate Parentheses
///
/// Given `n` pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
///
/// Example 1:
/// Input: n = 3
/// Output: ["((()))","(()())","(())()","()(())","()()()"]
///
/// Example 2:
/// Input: n = 1
/// Output: ["()"]
///
/// # Solution:
///
/// Time complexity: O(4^n)
/// Space complexity: O(n)
impl Solution {
pub fn generate_parenthesis(n: i32) -> Vec<String> {
let mut result = Vec::new();
fn backtrack(
current: &mut String,
open: i32,
close: i32,
max: i32,
result: &mut Vec<String>,
) {
if current.len() as i32 == max * 2 {
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();
}
}
backtrack(&mut String::new(), 0, 0, n, &mut result);
result
}
}