|
1 | 1 | pub struct Solution {}
|
2 | 2 |
|
3 | 3 | impl Solution {
|
4 |
| - pub fn generate_parenthesis(n: i32) -> Vec<String> {} |
| 4 | + pub fn generate_parenthesis(n: i32) -> Vec<String> { |
| 5 | + if n == 1 { |
| 6 | + return vec!["()".to_string()]; |
| 7 | + } |
| 8 | + let mut result = Vec::new(); |
| 9 | + for r in Self::generate_parenthesis(n - 1) { |
| 10 | + result.push(format!("({})", r)); |
| 11 | + let s1 = format!("(){}", r); |
| 12 | + let s2 = format!("{}()", r); |
| 13 | + if s2 != s1 { |
| 14 | + result.push(s2); |
| 15 | + } |
| 16 | + result.push(s1); |
| 17 | + } |
| 18 | + result |
| 19 | + } |
5 | 20 | }
|
6 | 21 |
|
7 | 22 | #[cfg(test)]
|
8 | 23 | mod tests {
|
9 | 24 | use super::*;
|
10 | 25 |
|
| 26 | + fn it_works(n: i32, expected: Vec<&str>) { |
| 27 | + let mut result = Solution::generate_parenthesis(n); |
| 28 | + let mut exp = expected.to_vec(); |
| 29 | + result.sort(); |
| 30 | + exp.sort(); |
| 31 | + assert_eq!(result, exp); |
| 32 | + } |
| 33 | + |
11 | 34 | #[test]
|
12 | 35 | fn example_1() {
|
13 | 36 | let n = 3;
|
14 | 37 | let expected = ["((()))", "(()())", "(())()", "()(())", "()()()"];
|
15 |
| - assert_eq!(Solution::generate_parenthesis(n), expected.to_vec()); |
| 38 | + it_works(n, expected.to_vec()); |
16 | 39 | }
|
17 | 40 |
|
18 | 41 | #[test]
|
19 | 42 | fn example_2() {
|
20 | 43 | let n = 1;
|
21 | 44 | let expected = ["()"];
|
22 |
| - assert_eq!(Solution::generate_parenthesis(n), expected.to_vec()); |
| 45 | + it_works(n, expected.to_vec()); |
| 46 | + } |
| 47 | + |
| 48 | + #[test] |
| 49 | + fn submission_1() { |
| 50 | + let n = 4; |
| 51 | + let expected = [ |
| 52 | + "(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", |
| 53 | + "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()", |
| 54 | + ]; |
| 55 | + it_works(n, expected.to_vec()); |
23 | 56 | }
|
24 | 57 | }
|
0 commit comments