1 Star 0 Fork 0

iint/notes

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
20201028dzh.md
20210505大组会.md
210服务器使用方法.md
4MedianofTwoSortedArray.md
51单片机.md
8大主流服务器程序线程模型.md
ArrayList与LinkedList.md
BNCT.md
C#正则表达式.md
C++的typedef.md
C连接mysql.md
FCN.md
G401.md
History命令用法.md
Interpretbytesaspackedbinarydata.md
IoU.md
K-means聚类算法的理解与案例实战.md
Liner Models.md
Linux下快速比较两个目录的不同.md
MRI-CT工作的数据处理02.md
MRI-CT工作的数据处理03.md
MRI-CT工作的数据处理全过程.md
MRI-CT工作的数据预处理01.md
MRI-CT工作的结果分析01.md
MySQL学习笔记.md
OFDR技术.md
PCA.md
PIL图像处理库简介.md
Paper210309_深度学习预测剂量分布.md
PyTorch常用代码段整理.md
Pythonlambda介绍.md
Pythonxrange()函数.md
Python与C的交互.md
Python中os.sep.join()和os.path.join()的用法和区别.md
Python利用生成器读取大文件数据.md
Python可视化.md
Python将字符串作为变量名.md
Python常用的内建模块.md
Python常用第三方模块.md
Python标准库shutil用法实例详解.md
Python正则表达式.md
Python直接反投影重建CT.md
Python类型注解.md
Python类装饰器.md
Python计算皮尔逊相关系数.md
Python通过钩子远程加载模块.md
Python静态类方法.md
Pytorch中train和eval用法区别.md
Pytorch的BatchNorm层使用中容易出现的问题.md
Pytorch的transforms.md
SQL高质量语句.md
Ubuntu压缩及解压文件.md
__slots__是个什么玩意儿.md
batch_normalization.md
centos7 计划任务 定时运行sh.md
conda.md
cpp list node.md
cpp11并发与多线程.md
cppSTLunordered_map容器用法详解.md
cpphashmap.md
cpp中auto类型用法总结.md
cpp中const的用法.md
cpp中lambda函数.md
cpp中malloc、calloc、realloc函数的用法.md
cpp中set用法详解.md
cpp中using的用法.md
cpp中减去'0'的作用(-'0').md
cpp中的内联函数.md
cpp之namespace常见用法.md
cpp信号处理.md
cpp基础.md
cpp左值引用和右值引用.md
cpp异常处理trycatchthrow.md
cpp提高.md
cpp文件读写.md
cpp核心.md
cpp类中成员变量的初始化.md
cpp预处理器.md
effectivePython.md
github_tutorial.md
https与http.md
k折交叉验证.md
latex.md
leetcode-001.md
leetcode1.TwoSum.md
leetcode11.ContainerWithMostWater.md
leetcode12.IntegertoRoman.md
leetcode131.PalindromePartitioning.md
leetcode15.3Sum.md
leetcode17.LetterCombinationsofaPhoneNumber.md
leetcode22.GenerateParentheses.md
leetcode24.SwapNodesinPairs.md
leetcode3.LongestSubstringWithoutRepeatingCharacters.md
leetcode39.CombinationSum.md
leetcode43.MultiplyStrings.md
leetcode5.LongestPalindromicSubstring.md
leetcode6.ZigZagConversion.md
matplotlib colorbar颜色卡自定义偏移量.md
matplotlib.md
matplotlib_tutorial.md
matplotlib的一些小技巧.md
matplotlib风格.md
mcgpu.md
mysql批量删除重复行.md
namedtuple的使用.md
numpy索引和切片.md
office正则.md
pandas.md
pychram快捷键.md
python-mvisdom.server报[Errno98]Addressalreadyinuse错误解决办法.md
python.md
python_cookbook.md
python关于sorted里面key,reverse以及lamdba,operator这几个鸟人.md
python发送邮件.md
python拟合曲线.md
python正则.md
python爬虫实例-iint入组培训.md
python获取当前目录下的所有文件.md
python装饰器.md
python调用dll动态链接库及ctypes的使用.md
python透明图片和不透明图片叠加合成.md
python闭包.md
python骚操作.md
pytorch分割二分类的两种形式.md
pytorch分布式.md
reids是什么.md
shell.md
shell_cookbook.md
str和repr.md
tqdm.md
vector的六种创建和初始化方法.md
visdom服务启动时提示Downloadingscripts,thismaytakealittlewhile解决...
wordpress迁移.md
yolact.md
中值滤波优化图像结果.md
为什么说relu是激活函数.md
云南旅游计划.md
什么是cpp.md
什么是图神经网络.md
从贝叶斯方法谈到贝叶斯网络.md
优势:杀死乏氧细胞乏氧细胞定义.md
传能线密度.md
使用Python把超大文件当成数组读取.md
共线性.md
利用python快速发送博客到wordpress.md
制作h5py数据集.md
医学图像分割数据集制作.md
医学影像一些概念.md
单例模式.md
南航高性能计算平台介绍.md
卷积的优化.md
原理这就是网络.md
口诀理解Python闭包与装饰器.md
回调函数callback.md
图像分割损失函数设计.md
图像的全变分和去噪.md
基于深度学习的自然图像和医学图像分割:网络结构设计.md
基于蝴蝶网络的双能CT图像域双材料分解.md
多级反馈队列调度算法详解.md
大组会文献汇报.md
安装私有的包.md
将CT值转换为器官组织的one_hot编码.md
工厂模式.md
常见分类算法及他们的优缺点.md
平衡二叉树、B树、B+树、B树.md
应用层.md
快速理解numpy的axis.md
批量删除excel单元格中的换行符.md
损失函数在医学图像分割问题中的应用.md
数值分析作业01.md
数据降维.md
数理逻辑——命题逻辑的基本概念.md
朴素贝叶斯原理及python实现.md
机器学习中,频率派和贝叶斯派有什么核心差异?.md
机器学习十大算法.md
深度学习调参技巧.md
理解主成分分析.md
用Pytorch踩过的坑.md
用python更新主图数据库.md
白化.md
硼中子俘获治疗.md
神经网络不收敛的11个问题.md
神经网络中的注意力机制.md
神经网络工作基本流程.md
群论.md
自动抢羽毛球馆预约.md
英语演讲稿.md
计算机网络.md
计算机网络01-概念、基础.md
设计模式.md
详解AVL树基础篇.md
读写二进制数组数据.md
贝叶斯vs频率派.md
迭代.md
阿里云oss搭建个人图床和网盘.md
雷登变换.md
顺序容器.md
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
leetcode22.GenerateParentheses.md 7.13 KB
一键复制 编辑 原始数据 按行查看 历史
nuaazs 提交于 4年前 . first

## 22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

Input: n = 1
Output: ["()"]

Constraints:

  • 1 <= n <= 8

Solutions

Approach 1: Brute Force

Intuition

We can generate all 2^{2n}22n sequences of '(' and ')' characters. Then, we will check if each one is valid.

Algorithm

To generate all sequences, we use a recursion. All sequences of length n is just '(' plus all sequences of length n-1, and then ')' plus all sequences of length n-1.

To check whether a sequence is valid, we keep track of balance, the net number of opening brackets minus closing brackets. If it falls below zero at any time, or doesn't end in zero, the sequence is invalid - otherwise it is valid.

class Solution(object):
    def generateParenthesis(self, n):
        def generate(A = []):
            if len(A) == 2*n:
                if valid(A):
                    ans.append("".join(A))
                else:
                    A.append('(')
                    generate(A)
                    A.pop()
                    A.append(')')
                    generate(A)
                    A.pop()
        def valid(A):
            bal = 0
            for c in A:
                if c =='(':bal += 1
                else:bal-=1
                if bal<0:return False
            return bal == 0
        ans = []
        generate()
        return ans
class Solution{
    public List<String> generateParenthesis(int n){
        List<String> combinations = new ArrayList();
        generateAll(new char[2*n], 0, combinations);
        return combinations;
    }
    public void generateAll(char[] current, int pos, List<String> result){
        if(pos == current.length){
            if (valid(current))
                result.add(new String(current));
        } else {
            current[pos]='(';
            genereateAll(current, pos+1, result);
            current[pos]=')';
            generateAll(current, pos+1, result);
        }
    }
    public boolean valid(char[] current){
        int balance = 0;
        for (char c:current){
            if (c == '(') balance ++;
            else balance--;
            if (balance<0) return false;
        }
        return (balance == 0);
    }
}

Complexity Analysis

  • Time Complexity : O(2^{2n}n)O(22n**n). For each of 2^{2n}22n sequences, we need to create and validate the sequence, which takes O(n)O(n) work.
  • Space Complexity : O(2^{2n}n)O(22n**n). Naively, every sequence could be valid.

Approach 2: Backtracking

Intuition and Algorithm

Instead of adding '(' or ')' every time as in Approach 1, let's only add them when we know it will remain a valid sequence. We can do this by keeping track of the number of opening and closing brackets we have placed so far.

We can start an opening bracket if we still have one (of n) left to place. And we can start a closing bracket if it would not exceed the number of opening brackets.

class Solution(object):
    def generateParenthesis(self, N):
        ans = []
        def backtrack(S='', left=0, right=0):
            if len(S) == 2*N:
                ans.append(S)
                return
            if left<N:
                backtrack(S+'(',left+1,right)
            if right<left:
                backtrack(S+')', left, right+1)
        backtrack()
        return ans
class Solution{
    public List<String> generateParenthesis(int n){
        List<String> ans = new ArrayList();
        backtrack(ans,"",0,0,n);
        return ans;
    }
    public void backtrack(List<String> ans, String cur, int open, int close, int max){
        if(cur.length() == max *2){
            ans.add(cur);
            return;
        }
        
        if(open<max)
            backtrack(ans, cur+"(", open+1, close, max);
        if(close<open)
            backtrack(ans, cur+")", open, close+1, max);
    }
}

Complexity Analysis

Our complexity analysis rests on understanding how many elements there are in generateParenthesis(n). This analysis is outside the scope of this article, but it turns out this is the n-th Catalan number , which is bounded asymptotically by

  • Time Complexity : . Each valid sequence has at most n steps during the backtracking procedure.
  • Space Complexity :, as described above, and using O(n)O(n) space to store the sequence.

Approach 3: Closure Number

Intuition

To enumerate something, generally we would like to express it as a sum of disjoint subsets that are easier to count.

Consider the closure number of a valid parentheses sequence S: the least index >= 0 so that S[0], S[1], ..., S[2*index+1] is valid. Clearly, every parentheses sequence has a unique closure number. We can try to enumerate them individually.

Algorithm

For each closure number c, we know the starting and ending brackets must be at index 0 and 2*c + 1. Then, the 2*c elements between must be a valid sequence, plus the rest of the elements must be a valid sequence.

class Solution(object):
    def genereateParenthesis(self, N):
        if N == 0: return['']
        ans = []
        for c in xrange(N):
            for left in self.generateParenthesis(c):
                for right in self.generateParenthesis(N-1-c):
                    ans.append('({}){}'.format(left,right))
        return ans
class Solution{
    public List<String> generateParenthesis(int n){
        List<String> ans = new ArrayList();
        if (n == 0){
            ans.add("");
        } else {
            for (int c = 0; c<n; ++c)
                for (String left: generateParenthesis(c))
                    for (String right: generateParenthesis(n-1-c))
                        ans.add("("+left+")"+right);
        }
        return ans;
    }
}

Complexity Analysis

The idea is intuitive. Use two integers to count the remaining left parenthesis (n) and the right parenthesis (m) to be added. At each function call add a left parenthesis if n >0 and add a right parenthesis if m>0. Append the result and terminate recursive calls when both m and n are zero.

class Solution{
    public:
    vector<string> generateParenthesis(int n){
        vector<string> res;
        addingpar(res,"",n,0);
        return res;
    }
    void addingpar(vector<string> &v, string str, int n, int m){
        if(n == 0 && m == 0){
            v.push_back(str);
            return;
        }
        if(m>0){addingpar(v,str+")",n,m-1);}
        if(n>0){addingpar(v,str+"(",n-1,m+1);}
    }
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/iint/notes.git
git@gitee.com:iint/notes.git
iint
notes
notes
master

搜索帮助