-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0022_generate_parentheses.rs
More file actions
41 lines (36 loc) · 999 Bytes
/
s0022_generate_parentheses.rs
File metadata and controls
41 lines (36 loc) · 999 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
37
38
39
40
41
#![allow(unused)]
pub struct Solution {}
impl Solution {
pub fn generate_parenthesis(n: i32) -> Vec<String> {
let mut ans = vec![];
Self::backtrack(&mut ans, "".to_owned(), 0, 0, n);
ans
}
fn backtrack(ans: &mut Vec<String>, mut cur: String, open: i32, close: i32, max: i32) {
if cur.len() == max as usize * 2 {
ans.push(cur);
return;
}
if open < max {
let mut ret = cur.clone();
ret.push('(');
Self::backtrack(ans, ret, open + 1, close, max);
}
if close < open {
cur.push(')');
Self::backtrack(ans, cur, open, close + 1, max);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_22() {
assert_eq!(
Solution::generate_parenthesis(3),
["((()))", "(()())", "(())()", "()(())", "()()()",]
);
assert_eq!(Solution::generate_parenthesis(1), ["()",]);
}
}