How to generate parentheses in leetcode
Editor to share with you how to achieve parenthesis generation in leetcode, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
Parenthesis generation
The number n represents the logarithm of generating parentheses. Please design a function that can generate all possible and valid combinations of parentheses.
Example: input: n = 3 output: ["(())", "() ()", "()"]
Test site: dfs or dynamic planning
Train of thought:
The idea of iteration, the quantitative relationship between left and right parentheses
Dynamic programming, divided into'('+ good_l +')'+ good right
Class Solution: def generateParenthesis (self, n: int)-> List [str]: if n is None or n
< 1: return [] res = [] # 递归,左右括号的数量 ''' def helper(s, l, r): if l == 0 and r == 0: res.append(s) if l >0: helper (helper'(', lmur1, r) if r > l: helper (smiles')', l, rmur1) if r > l: return helper ('', n) N) return res''# dp # state transfer equation: DP [I] ='('+ dp [j] +')'+ dp [i-j-1] # consists of two parts # dp [I] represents a valid parenthesis combination of I pairs of parentheses dp = [None] * (naugh1) dp [0] = [''] for i in range (1) Cur = [] for j in range (I): left = dp [j] right = dp [i-j-1] for S1 in left: for S2 in right: cur.append ('('+ S1 +')'+ S2) Dp [I] = cur return dp [n]
The above is all the contents of the article "how to generate parentheses in leetcode". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!