-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
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
vil02
merged 9 commits into
TheAlgorithms:master
from
sozelfist:backtracking/gen-parents
May 16, 2024
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
abab5ab
chore: add `parentheses_generator.rs` to DIRECTORY.md
sozelfist ae8e6a3
feat: implement Parentheses Generator algorithm
sozelfist 3debf7d
chore: rename `open` to `open_count`, `close` to `close_count`
sozelfist 8707394
chore: change `u32` to `usize`
sozelfist 2b6e748
ref: eliminate the need for mutability
sozelfist 42765fd
chore: handle case where `n = 0`
sozelfist b8d7c83
chore: fix typos in docstring
sozelfist eaa3919
Merge branch 'master' into backtracking/gen-parents
vil02 9af207a
style: simplify logic
vil02 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!["(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()"]), | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.