Skip to content

Commit 36ec9fe

Browse files
committed
feat: add more
1 parent aa9394a commit 36ec9fe

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

stack/_0022_generate_parentheses.rs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// https://leetcode.com/problems/generate-parentheses
2+
//
3+
// Given `n` pairs of parentheses, write a function to _generate all combinations of well-formed parentheses_.
4+
//
5+
// **Example 1:**
6+
//
7+
// ```
8+
// **Input:** n = 3
9+
// **Output:** ["((()))","(()())","(())()","()(())","()()()"]
10+
// ```
11+
//
12+
// **Example 2:**
13+
//
14+
// ```
15+
// **Input:** n = 1
16+
// **Output:** ["()"]
17+
// ```
18+
//
19+
// **Constraints:**
20+
//
21+
// * `1 <= n <= 8`
22+
23+
pub fn generate_parenthesis(n: i32) -> Vec<String> {
24+
let mut res = vec![];
25+
fn backtrack(
26+
n: i32,
27+
open_count: i32,
28+
close_count: i32,
29+
cur: &mut String,
30+
res: &mut Vec<String>,
31+
) {
32+
if open_count == n && close_count == n {
33+
res.push(cur.clone());
34+
return;
35+
}
36+
if open_count < n {
37+
cur.push('(');
38+
backtrack(n, open_count + 1, close_count, cur, res);
39+
cur.pop();
40+
}
41+
if close_count < open_count {
42+
cur.push(')');
43+
backtrack(n, open_count, close_count + 1, cur, res);
44+
cur.pop();
45+
}
46+
}
47+
48+
backtrack(n, 0, 0, &mut String::new(), &mut res);
49+
return res;
50+
}
51+
52+
#[test]
53+
pub fn t1() {
54+
assert_eq!(
55+
generate_parenthesis(3),
56+
vec![
57+
"((()))".to_string(),
58+
"(()())".to_string(),
59+
"(())()".to_string(),
60+
"()(())".to_string(),
61+
"()()()".to_string(),
62+
]
63+
);
64+
}

stack/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#![allow(dead_code)]
22

33
mod _0020_valid_parentheses;
4+
mod _0022_generate_parentheses;
45
mod _0155_min_stack;
56
mod _1598_crawler_log_folder;

0 commit comments

Comments
 (0)