From 2945497f048d1b4d14ea9af4c5ce00876f3a7644 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 7 Jul 2024 09:35:10 +0800 Subject: [PATCH] 20240707 Finished --- src/problem/mod.rs | 3 +- src/problem/p22_generate_parentheses.rs | 50 +++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 src/problem/p22_generate_parentheses.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 78345f3..74738eb 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -168,4 +168,5 @@ mod p212_word_search_ii; mod p17_letter_combinations_of_a_phone_number; mod p77_combinations; mod p46_permutations; -mod p39_combination_sum; \ No newline at end of file +mod p39_combination_sum; +mod p22_generate_parentheses; \ No newline at end of file diff --git a/src/problem/p22_generate_parentheses.rs b/src/problem/p22_generate_parentheses.rs new file mode 100644 index 0000000..efee0f5 --- /dev/null +++ b/src/problem/p22_generate_parentheses.rs @@ -0,0 +1,50 @@ +/** + * [22] Generate Parentheses + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn generate_parenthesis(n: i32) -> Vec { + let n = n as usize; + let mut result = vec![]; + let mut path = Vec::with_capacity(n * 2); + + Self::backtrace(n, 0, &mut path, &mut result); + + result + } + + fn backtrace(left: usize, right: usize, path: &mut Vec, result: &mut Vec) { + if left == 0 && right == 0 { + let t = path.clone(); + result.push(t.iter().collect()); + return; + } + + if left != 0 { + path.push('('); + Self::backtrace(left - 1, right + 1, path, result); + path.pop(); + } + + if right != 0 { + path.push(')'); + Self::backtrace(left, right - 1, path, result); + path.pop(); + } + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_22() { + } +}