Skip to content

Commit 9c65648

Browse files
committed
q22
1 parent 5bb82d8 commit 9c65648

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

src/backtrace/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
mod q22;

src/backtrace/q22.rs

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
//! 数字 n代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
2+
//!
3+
//!
4+
//! 示例 1:
5+
//!
6+
//! 输入:n = 3
7+
//! 输出:["((()))","(()())","(())()","()(())","()()()"]
8+
//! 示例 2:
9+
//!
10+
//! 输入:n = 1
11+
//! 输出:["()"]
12+
//!
13+
14+
15+
struct Solution();
16+
impl Solution {
17+
pub fn generate_parenthesis(n: i32) -> Vec<String> {
18+
19+
20+
fn back_track(s: String, open: i32, close: i32) -> Vec<String> {
21+
let mut res = vec![];
22+
23+
if open == 0 && close == 0 {
24+
return vec![s.to_owned()]
25+
}
26+
27+
if open > 0 {
28+
res.append(&mut back_track(s.clone()+"(", open-1, close+1));
29+
}
30+
31+
if close > 0 {
32+
res.append(&mut back_track(s.clone()+")", open.clone(), close-1));
33+
}
34+
res
35+
36+
}
37+
38+
back_track("".to_owned(), n, 0)
39+
}
40+
}
41+
42+
43+
44+
45+
#[cfg(test)]
46+
mod tests {
47+
use super::*;
48+
49+
#[test]
50+
fn it_works() {
51+
let result = Solution::generate_parenthesis(2);
52+
println!("{:?}", result);
53+
assert_eq!(result.len(), 2);
54+
assert!(result.contains(&"(())".to_owned()));
55+
assert!(result.contains(&"()()".to_owned()));
56+
57+
}
58+
}

0 commit comments

Comments
 (0)