Skip to content

Implement Parentheses Generator using Backtracking Strategy #713

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* [All Combination Of Size K](https://github.com/TheAlgorithms/Rust/blob/master/src/backtracking/all_combination_of_size_k.rs)
* [Knight Tour](https://github.com/TheAlgorithms/Rust/blob/master/src/backtracking/knight_tour.rs)
* [N Queens](https://github.com/TheAlgorithms/Rust/blob/master/src/backtracking/n_queens.rs)
* [Parentheses Generator](https://github.com/TheAlgorithms/Rust/blob/master/src/backtracking/parentheses_generator.rs)
* [Permutations](https://github.com/TheAlgorithms/Rust/blob/master/src/backtracking/permutations.rs)
* [Sudoku](https://github.com/TheAlgorithms/Rust/blob/master/src/backtracking/sudoku.rs)
* Big Integer
Expand Down
2 changes: 2 additions & 0 deletions src/backtracking/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
mod all_combination_of_size_k;
mod knight_tour;
mod n_queens;
mod parentheses_generator;
mod permutations;
mod sudoku;

pub use all_combination_of_size_k::generate_all_combinations;
pub use knight_tour::find_knight_tour;
pub use n_queens::n_queens_solver;
pub use parentheses_generator::generate_parentheses;
pub use permutations::permute;
pub use sudoku::Sudoku;
76 changes: 76 additions & 0 deletions src/backtracking/parentheses_generator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/// Generates all combinations of well-formed parentheses given a non-negative integer `n`.
///
/// This function uses backtracking to generate all possible combinations of well-formed
/// parentheses. The resulting combinations are returned as a vector of strings.
///
/// # Arguments
///
/// * `n` - A non-negative integer representing the number of pairs of parentheses.
pub fn generate_parentheses(n: usize) -> Vec<String> {
let mut result = Vec::new();
if n > 0 {
generate("", 0, 0, n, &mut result);
}
result
}

/// Helper function for generating parentheses recursively.
///
/// This function is called recursively to build combinations of well-formed parentheses.
/// It tracks the number of open and close parentheses added so far and adds a new parenthesis
/// if it's valid to do so.
///
/// # Arguments
///
/// * `current` - The current string of parentheses being built.
/// * `open_count` - The count of open parentheses in the current string.
/// * `close_count` - The count of close parentheses in the current string.
/// * `n` - The total number of pairs of parentheses to be generated.
/// * `result` - A mutable reference to the vector storing the generated combinations.
fn generate(
current: &str,
open_count: usize,
close_count: usize,
n: usize,
result: &mut Vec<String>,
) {
if current.len() == (n * 2) {
result.push(current.to_string());
return;
}

if open_count < n {
let new_str = current.to_string() + "(";
generate(&new_str, open_count + 1, close_count, n, result);
}

if close_count < open_count {
let new_str = current.to_string() + ")";
generate(&new_str, open_count, close_count + 1, n, result);
}
}

#[cfg(test)]
mod tests {
use super::*;

macro_rules! generate_parentheses_tests {
($($name:ident: $test_case:expr,)*) => {
$(
#[test]
fn $name() {
let (n, expected_result) = $test_case;
assert_eq!(generate_parentheses(n), expected_result);
}
)*
};
}

generate_parentheses_tests! {
test_generate_parentheses_0: (0, Vec::<String>::new()),
test_generate_parentheses_1: (1, vec!["()"]),
test_generate_parentheses_2: (2, vec!["(())", "()()"]),
test_generate_parentheses_3: (3, vec!["((()))", "(()())", "(())()", "()(())", "()()()"]),
test_generate_parentheses_4: (4, vec!["(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()"]),
}
}