c_cpp 给定n对括号,编写一个函数来生成格式正确的括号的所有组合。例如,给定n = 3,解决方案
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 给定n对括号,编写一个函数来生成格式正确的括号的所有组合。例如,给定n = 3,解决方案相关的知识,希望对你有一定的参考价值。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void helper(vector<string> &res, string s, int left, int right, int n) {
if(left == n && right == n) {
res.push_back(s);
return;
}
if(left < n)
helper(res, s + "(", left + 1, right, n);
if(left > right) {
helper(res, s + ")", left, right + 1, n);
}
}
h(res, "", 0, 0, 3)
{
h(res, "(", 1, 0, 3){
h(res, "((", 2, 0, 3){
h(res, "(((", 3, 0, 3){
h(res, "((()", 3, 1, 3){
h(res, "((())", 3, 2, 3){
h(res, "((()))", 3, 3, 3); // done
}
}
}
h(res, "(()", 2, 1, 3){
h(res, "(()(", 3, 1, 3){
h(res, "(()()", 3, 2, 3){
h(res, "(()())", 3, 3, 3); // done
}
}
h(res, "(())", 2, 2, 3){
h(res, "(())(", 3, 2, 3){
h(res, "(())()", 3, 3, 3); // done
}
}
}
}
h(res, "()", 1, 1, 3){
h(res, "()(", 2, 1, 3){
h(res, "()((", 3, 1, 3){
h(res, "()(()", 3, 2, 3){
h(res, "()(())", 3, 3, 3); // done
}
}
h(res, "()()", 2, 2, 3){
h(res, "()()(", 3, 2, 3){
h(res, "()()()", 3, 3, 3); // done
}
}
}
}
}
}
vector<string> generate_parenthesis(int n) {
vector<string> res;
string s;
helper(res, s, 0, 0, n);
return res;
}
int main()
{
vector<string> res = generate_parenthesis(3);
for(string t : res)
cout << t << endl;
return 0;
}
以上是关于c_cpp 给定n对括号,编写一个函数来生成格式正确的括号的所有组合。例如,给定n = 3,解决方案的主要内容,如果未能解决你的问题,请参考以下文章
LintCode刷题——生成括号
LeetCode第[22]题(Java):Generate Parentheses
lintcode: 生成括号
c_cpp 编写一个函数来检查给定字符串是否与给定模式匹配为非连续子字符串:即,模式中的所有字符
编写自定义函数,求水仙花数,并输出
c_cpp [螺旋矩阵II]:给定整数n,生成以螺旋顺序填充1到n2的元素的方阵。例如,给定n =