LeetCode22. 括号生成

题目

分析

 

 关于合法的括号序列的重要推论

一个合法的括号序列的充要条件 :1. 任意前缀中 '(' 的数量 大于等于 ')' 的数量  2. 左右'(' ')'括号的数量相等

n对括号组成的合法括号序列的个数为 卡特兰数 !!!

以上结论非常重要!!!

代码

yxc 老师版本

 1 class Solution {
 2 public:
 3     vector<string>ans;
 4     //string path;
 5   //lc,rc代表左右括号数量
 6     void dfs(int n, int lc,int rc,string path){
 7         if(lc == n && rc == n) ans.push_back(path);
 8         else{
 9             if(lc < n) dfs(n,lc+1,rc,path + '(');
10             if(rc < n && lc > rc) dfs(n,lc,rc+1,path+')');
11         }
12     }
13     vector<string> generateParenthesis(int n) {
14         dfs(n,0,0,"");
15         return ans;
16     }
17 };

 

自己版本

 1 class Solution {
 2 public:
 3     vector<string> ans;
 4     string path;
 5 
 6     void dfs(int n, int lc,int rc,string path){
 7         if(lc == n && rc == n) ans.push_back(path);
 8         else{
 9             if(lc < n ){
10                 path = path + '(';
11                 dfs(n,lc + 1, rc,path);
12                 path.pop_back();
13             }
14             if(rc < n && lc > rc){
15                 path = path + ')';
16                 dfs(n,lc,rc + 1, path);
17                 path.pop_back();
18             }
19         }
20     }
21     vector<string> generateParenthesis(int n) {
22         dfs(n,0,0,"");
23         return ans;
24     }   
25 };

两种本质上差不多,只是闫老师喜欢path 路径传到参数中,这样写就不用返回上文了,而自己喜欢把path 作为全局变量,这样还需要返回上文,闫老师代码确实清爽!!

 

时间复杂度的话,为组合数C(n,2n),因为总共有卡特兰数种情况,再将结果复制放到ans 里面,一个合法字符串为2n,二者相乘即为C(n,2n)

posted @ 2022-03-28 21:18  Uitachi  阅读(27)  评论(0编辑  收藏  举报