一、题目说明

这个题目是22. Generate Parentheses,简单来说,输入一个数字n,输出n对匹配的小括号。

简单考虑了一下,n=0,输出"";n=1,输出“()”;n=2,输出“()()”,"(())"...

二、我的解法

我考虑了一下,基本上2种思路,其1是暴力破解法,就是列出所有可能情况,然后判断哪些是匹配的。

汗颜的是,我没做出来。找到的答案:

#include<iostream>
#include<vector>
#include<string>
using namespace std; class Solution {
public:
//Brute Force
vector<string> generateParenthesis(int n) {
int num = 2*n;
string cur(num,'0');
vector<string> ans;
//1左移num位得到2的2*n次方
for (int v = (1<<num)-1; v > 0; v--) {
//生成 所有的0、1序列
// for (int i = 0; i < num; i++) {
// if(v & 1<<i) cur[i] = '(';
// else cur[i]=')';
// }
// ans.push_back(cur); int cnt = 0;
for (int i = 0; i < num; i++) {
if (v&1<<i) { cur[i]='('; cnt++; }
else { cur[i]=')'; cnt--; }
if (cnt < 0 || cnt > n) break;
}
if (cnt == 0) ans.push_back(cur);
}
return ans;
}; void test(int n){
string cur(n,'0');
for(int v=(1<<n)-1;v>=0;v--){
for(int j=0;j<n;j++){
if(v & 1<<j) cur[j] = '1';
else cur[j] = '0';
}
cout<<cur<<"\n";
}
}
}; int main(){
Solution s;
// s.test(2);
vector<string> r = s.generateParenthesis(1);
cout<<r.size()<<endl;
for(int i=0;i<r.size();i++){
cout<<r[i]<<endl;
}
return 0;
}

其2是回溯法,汗颜的是,我也没做出来,网上找到的答案:

#include<iostream>
#include<vector>
using namespace std; class Solution {
public: //Backtracking
vector<string> generateParenthesis(int n)
{
if(!n) return vector<string>(1, "");
if(n == 1) return vector<string>(1, "()"); vector<string> result; for(int i = n-1; i >=0; i--)
{
vector<string> inner = generateParenthesis(i);
vector<string> outer = generateParenthesis(n-i-1); for(int i=0; i < inner.size(); i++)
for(int j=0; j < outer.size(); j++)
result.push_back( "(" + inner[i] + ")" + outer[j] );
} return result;
}
};
int main(){
Solution s;
vector<string> r = s.generateParenthesis(3);
for(int i=0;i<r.size();i++){
cout<<r[i]<<endl;
}
return 0;
}

三、优化措施

另外,学过离散数学的,还有一种方法就是“闭包”。似曾相识,直接上答案:

class Solution {
public: //Imporved Closure Number
vector<string> generateParenthesis(int n) {
map<int, vector<string>> map;
map[0].push_back("");
for(int i = 1; i <= n; i++)
for(int c = 0; c < i; c++)
for(string left: map[c])
for(string right: map[i - 1 - c])
map[i].push_back("(" + left + ")" + right);
return map[n];
}
};

最新文章

  1. 在C#代码中应用Log4Net(三)Log4Net中配置文件的解释
  2. php大力力 [052节] php数据库页面修改功能
  3. Android UI 绘制过程浅析(四)draw过程
  4. 我和Java有个约定
  5. WebStorm设置编辑器中的字体大小
  6. iOS开发 使用RMStore简化内购代码 + 内购买订单验证
  7. ssi服务器端指令
  8. ajax跨域请求,页面和java服务端的写法
  9. 前端--关于javascript函数
  10. 改善C#公共程序类库质量的10种方法和工具
  11. UWP 使用OneDrive云存储2.x api(一)【全网首发】
  12. NewLife.Net——开始网络编程
  13. 15.app后端怎么设计用户登录方案
  14. technologies
  15. c++ 指针与const的三种组合
  16. Mac Terminal open app with a file opened
  17. c# 过滤html
  18. [jQ/PHP]再谈使用JS数组储值的运用(提交PHP处理)
  19. CentOS 7下KVM支持虚拟化/嵌套虚拟化配置
  20. Mockito 的使用

热门文章

  1. 普通版js运动框架
  2. http报文解析
  3. Hadoop之HDFS扩容方法
  4. 2python脚本在window编辑后linux不能执行的问题
  5. linux centos7安装mysql8
  6. Qt实践基础-简单的登录界面的实现
  7. 函数的默认值与动态参数arguments的总结
  8. 第3种方法获取redis cluster主从关系
  9. CF round 623 Div.1D Tourism 题解
  10. 剑指offer-面试题51-数组中的逆序对-归并排序