This commit is contained in:
Sainnhe Park 2022-11-14 10:27:21 +08:00
parent 2031712234
commit 1829bf176e
3 changed files with 69 additions and 0 deletions

View File

@ -0,0 +1,15 @@
#ifndef S0022_GENERATE_PARENTHESES
#define S0022_GENERATE_PARENTHESES
#include <vector>
#include <string>
#include <cmath>
using namespace std;
class Solution {
public:
vector<string> generateParenthesis(int n);
};
#endif

View File

@ -0,0 +1,30 @@
#include "s0022_generate_parentheses.hpp"
// 深度优先遍历:
// 接收参数为每个节点的状态
// 遍历结果可以用指针放在接收参数保存,也可以通过声明一个 class 的成员来保存
void dfs(string current, int left, int right, vector<string> &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<string> Solution::generateParenthesis(int n) {
// 初始化
vector<string> result = {};
dfs("", n, n, result);
return result;
}

View File

@ -0,0 +1,24 @@
#include "s0022_generate_parentheses.hpp"
#include <gtest/gtest.h>
TEST(Problem22, Case1) {
int i{3};
vector<string> o{"((()))", "(()())", "(())()", "()(())", "()()()"};
Solution solution;
EXPECT_EQ(solution.generateParenthesis(i), o);
}
TEST(Problem22, Case2) {
int i{1};
vector<string> o{"()"};
Solution solution;
EXPECT_EQ(solution.generateParenthesis(i), o);
}
TEST(Problem22, Case3) {
int i{4};
vector<string> o{"(((())))","((()()))","((())())","((()))()","(()(()))","(()()())","(()())()","(())(())","(())()()","()((()))","()(()())","()(())()","()()(())","()()()()"};
Solution solution;
EXPECT_EQ(solution.generateParenthesis(i), o);
}