pub struct Solution; impl Solution { pub fn generate_parenthesis(n: i32) -> Vec { let mut operations = vec![(0, 0, "".to_string())]; let mut result = vec![]; while let Some((left, right, s)) = operations.pop() { if s.len() == n as usize * 2 { result.push(s); continue; } if left < n { operations.push((left + 1, right, s.clone() + "(")); } if right < left { operations.push((left, right + 1, s + ")")); } } return result; } } #[cfg(test)] mod tests { use super::Solution; #[test] fn test1() { let mut actual = Solution::generate_parenthesis(3); actual.sort(); assert_eq!(actual, vec!["((()))","(()())","(())()","()(())","()()()"]); } #[test] fn test2() { assert_eq!(Solution::generate_parenthesis(1), vec!["()"]); } }