#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
class solution {
public:
static void generate_parenthesis(const char *path, int n) {
if (n <= 0) {
return;
}
if (1 == n) {
return;
}
if (n > 15) {
return;
}
char buf[1024] = "";
std::vector<std::vector<std::string>>dp(n + 1);
dp[0] = { "" };
dp[1] = { "()" };
for (int i = 2;i <= n;i++) {
for (int j = 0;j < i;j++) {
for (auto &p : dp[j]) {
for (auto &q : dp[i - j - 1]) {
snprintf(buf, sizeof(buf), "(%s)%s", p.c_str(), q.c_str());
dp[i].emplace_back(buf);
}
}
}
}
remove(path);
std::fstream fs(path, std::ios::out);
if (!fs) {
std::cerr << path << " open failed." << std::endl;
return;
}
for (auto &str : dp[n]) {
fs << str << std::endl;
}
fs.close();
dp.clear();
std::vector<std::vector<std::string>>{}.swap(dp);
}
};
int main() {
solution::generate_parenthesis("1.txt", 15);
return 0;
}
class Solution {
public:
vector<string> generateParenthesis(int n) {
char buf[1024] = "";
std::vector<std::vector<std::string>>dp(n + 1);
dp[0] = { "" };
dp[1] = { "()" };
for (int i = 2;i <= n;i++) {
for (int j = 0;j < i;j++) {
for (auto &p : dp[j]) {
for (auto &q : dp[i - j - 1]) {
snprintf(buf, sizeof(buf), "(%s)%s", p.c_str(), q.c_str());
dp[i].emplace_back(buf);
}
}
}
}
return dp[n];
}
};
leetcode 生成n阶括号
最新推荐文章于 2022-03-11 15:46:11 发布