Skip to content

Commit 7219b88

Browse files
author
Zhang Xiaodong
committed
solve 22
1 parent d26077c commit 7219b88

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@ mod s0018_4sum;
1717
mod s0019_remove_nth_node_from_end_of_list;
1818
mod s0020_valid_parentheses;
1919
mod s0021_merge_two_sorted_lists;
20+
mod s0022_generate_parentheses;
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/**
2+
* [22] 括号生成
3+
*
4+
* 数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
5+
*
6+
* 示例 1:
7+
*
8+
* 输入:n = 3
9+
* 输出:["((()))","(()())","(())()","()(())","()()()"]
10+
*
11+
* 示例 2:
12+
*
13+
* 输入:n = 1
14+
* 输出:["()"]
15+
*
16+
*
17+
* 提示:
18+
*
19+
* 1 <= n <= 8
20+
*
21+
*/
22+
pub struct Solution {}
23+
24+
// problem: https://leetcode.cn/problems/generate-parentheses/
25+
// discuss: https://leetcode.cn/problems/generate-parentheses/discuss/?currentPage=1&orderBy=most_votes&query=
26+
27+
// submission codes start here
28+
29+
impl Solution {
30+
pub fn generate_parenthesis(n: i32) -> Vec<String> {
31+
Self::gen(0, 0, n)
32+
}
33+
34+
fn gen(l: i32, r: i32, n: i32) -> Vec<String> {
35+
if l > n || l < r {
36+
return vec![];
37+
}
38+
if l == n && l == r {
39+
return vec!["".to_string()];
40+
}
41+
let mut res = vec![];
42+
let subs = Self::gen(l + 1, r, n);
43+
for s in subs {
44+
res.push(format!("({}", s));
45+
}
46+
let subs = Self::gen(l, r + 1, n);
47+
for s in subs {
48+
res.push(format!("){}", s));
49+
}
50+
res
51+
}
52+
}
53+
54+
// submission codes end
55+
56+
#[cfg(test)]
57+
mod tests {
58+
use super::*;
59+
60+
#[test]
61+
fn test_22() {
62+
assert_eq!(Solution::generate_parenthesis(1), vec!["()".to_string()]);
63+
assert_eq!(
64+
Solution::generate_parenthesis(3),
65+
vec!["((()))", "(()())", "(())()", "()(())", "()()()"]
66+
);
67+
}
68+
}

0 commit comments

Comments
 (0)