From 1829bf176ee5c2a545962e40fa1e37c24b12328c Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Mon, 14 Nov 2022 10:27:21 +0800 Subject: [PATCH] s0022 --- include/s0022_generate_parentheses.hpp | 15 +++++++++++++ src/s0022_generate_parentheses.cpp | 30 ++++++++++++++++++++++++++ tests/s0022_generate_parentheses.cpp | 24 +++++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 include/s0022_generate_parentheses.hpp create mode 100644 src/s0022_generate_parentheses.cpp create mode 100644 tests/s0022_generate_parentheses.cpp diff --git a/include/s0022_generate_parentheses.hpp b/include/s0022_generate_parentheses.hpp new file mode 100644 index 0000000..f5329d6 --- /dev/null +++ b/include/s0022_generate_parentheses.hpp @@ -0,0 +1,15 @@ +#ifndef S0022_GENERATE_PARENTHESES +#define S0022_GENERATE_PARENTHESES + +#include +#include +#include + +using namespace std; + +class Solution { + public: + vector generateParenthesis(int n); +}; + +#endif diff --git a/src/s0022_generate_parentheses.cpp b/src/s0022_generate_parentheses.cpp new file mode 100644 index 0000000..54459f8 --- /dev/null +++ b/src/s0022_generate_parentheses.cpp @@ -0,0 +1,30 @@ +#include "s0022_generate_parentheses.hpp" + +// 深度优先遍历: +// 接收参数为每个节点的状态 +// 遍历结果可以用指针放在接收参数保存,也可以通过声明一个 class 的成员来保存 +void dfs(string current, int left, int right, vector &result) { + // 讨论边界条件(结束条件) + // 不必讨论起始条件,因为初始化的工作会在 dfs 函数外完成。 + if (left == 0 && right == 0) { + result.push_back(current); + } + // 讨论越界或不合法状态,剪枝 + if (left > right) { + return; + } + // 合法状态,扩展到下一层 + if (left > 0) { + dfs(current + '(', left - 1, right, result); + } + if (right > 0) { + dfs(current + ')', left, right - 1, result); + } +} + +vector Solution::generateParenthesis(int n) { + // 初始化 + vector result = {}; + dfs("", n, n, result); + return result; +} diff --git a/tests/s0022_generate_parentheses.cpp b/tests/s0022_generate_parentheses.cpp new file mode 100644 index 0000000..402ea26 --- /dev/null +++ b/tests/s0022_generate_parentheses.cpp @@ -0,0 +1,24 @@ +#include "s0022_generate_parentheses.hpp" + +#include + +TEST(Problem22, Case1) { + int i{3}; + vector o{"((()))", "(()())", "(())()", "()(())", "()()()"}; + Solution solution; + EXPECT_EQ(solution.generateParenthesis(i), o); +} + +TEST(Problem22, Case2) { + int i{1}; + vector o{"()"}; + Solution solution; + EXPECT_EQ(solution.generateParenthesis(i), o); +} + +TEST(Problem22, Case3) { + int i{4}; + vector o{"(((())))","((()()))","((())())","((()))()","(()(()))","(()()())","(()())()","(())(())","(())()()","()((()))","()(()())","()(())()","()()(())","()()()()"}; + Solution solution; + EXPECT_EQ(solution.generateParenthesis(i), o); +}