给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
思路:
递归:
#include
#include
using namespace std;
void gen(int left,int right,string s,vector &ans)
{
if(right==) {ans.push_back(s); return ;}//右括号用完前,左括号早就用完了。所以返回
else if(left==right) gen(left-,right,s+'(',ans);//剩余的左括号数量=右括号数量时,只能放左括号
else if(left==) gen(left,right-,s+')',ans);//左括号都写进s中去了,后面只能写右括号了
else {gen(left,right-,s+')',ans);//除上面几种情况外,写左写右均可
gen(left-,right,s+'(',ans);
}
}
vector generateParenthesis(int n) {
vector ans;
gen(n,n,"",ans);
return ans;
}
int main() {
int n=;
vector ans;
ans=generateParenthesis(n);
cout<
return ;
}
LeetCode刷题笔记-回溯法-括号生成
题目描述: 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合. 例如,给出 n = 3,生成结果为: [ "((()))", "( ...
Leetcode之回溯法专题-22. 括号生成(Generate Parentheses)
Leetcode之回溯法专题-22. 括号生成(Generate Parentheses) 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合. 例如,给出 n ...
#leetcode刷题之路32-最长有效括号
给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度. 示例 1:输入: "(()"输出: 2解释: 最长有效括号子串为 "()"示 ...
#leetcode刷题之路20-有效的括号
#include #include #include using namespace std; bool i ...
python -- leetcode 刷题之路
第一题 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums = [2, 7, 11, 15], tar ...
使用Java+Kotlin双语言的LeetCode刷题之路(三)
BasedLeetCode LeetCode learning records based on Java,Kotlin,Python...Github 地址 序号对应 LeetCode 中题目序号 ...
使用Java+Kotlin双语言的LeetCode刷题之路(二)
BasedLeetCode LeetCode learning records based on Java,Kotlin,Python...Github 地址 序号对应 LeetCode 中题目序号 ...
使用Java+Kotlin双语言的LeetCode刷题之路(一)
LeetCode learning records based on Java,Kotlin,Python...Github 地址 序号对应 LeetCode 中题目序号 1 两数之和 给定一个整数数 ...
#leetcode刷题之路40-组合总和 II
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合.candidates 中的每个数字在每个组合中只能使用一次.说 ...
随机推荐
linux install Theano+Tensorflow+Keras
安装过程中,网络状态一定要好,如果安装过程中出现time out的提示信息,今天就可以洗洗睡啦,等明天网络状态好的时候再安装. 安装过程出现不知名的错误的时候,执行第一步,update一下 1.#up ...
ASP.NET前端语法应用
字符拼接
驱动10.nor flash
1 比较nor/nand flash NOR NAND接口: RAM-Like,引脚多 引脚少, ...
刘强1109 JavaScript基础二(分支与循环结构)
[if-else结构] 1.结构的写法: if(判断条件){ 条件为true时,执行if{} } else{ 条件为false时,执行else{} } 2.注意事项: ① else{}语句块,可以根据 ...
Windows系统JDK安装配置
JDK和JRE的安装 打开java的官方网站,下载安装程序,版本根据自己情况选择: 双击安装程序: 点击"下一步": 此处推荐默认路径安装,如果自定义安装目录,则需记住自定义的安装 ...
Vagrant 入门指南
https://blog.csdn.net/qianghaohao/article/details/80038096 https://blog.csdn.net/happyhorizion/artic ...
centos 远程授权
centos 远程授权命令 ssh-copy-id root@192.168.15.70
@RequestBody, @ResponseBody 注解详解(转)