20240707 Finished

This commit is contained in:
jackfiled 2024-07-07 09:35:10 +08:00
parent 39d326a642
commit 2945497f04
2 changed files with 52 additions and 1 deletions

View File

@ -168,4 +168,5 @@ mod p212_word_search_ii;
mod p17_letter_combinations_of_a_phone_number; mod p17_letter_combinations_of_a_phone_number;
mod p77_combinations; mod p77_combinations;
mod p46_permutations; mod p46_permutations;
mod p39_combination_sum; mod p39_combination_sum;
mod p22_generate_parentheses;

View File

@ -0,0 +1,50 @@
/**
* [22] Generate Parentheses
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn generate_parenthesis(n: i32) -> Vec<String> {
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<char>, result: &mut Vec<String>) {
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() {
}
}