Generate Parentheses

简介: Generate Parentheses 给定一个数字n,生成符合要求的n对括号 Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Generate Parentheses

给定一个数字n,生成符合要求的n对括号

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

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

 

 1 package com.rust.TestString;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 class solution {
 7     List<String> res = new ArrayList<String>();
 8     public List<String> generateParenthesis(int n) {
 9         if (n == 0) {
10             res.add("");
11             return res;
12         }
13         addBrackets("", 0, 0, n);//这个递归并没有返回的条件,跑到完为止
14         return res;
15     }
16     public void addBrackets(String str,int leftB,int rightB,int n) {
17         if (leftB == n && rightB == n) {
18             res.add(str);
19         }// 每次递归进来,根据现有情况,还会分割成不同的情况
20         if (leftB < n) {
21             addBrackets(str + "(", leftB + 1, rightB, n);
22         } 
23         if (rightB < leftB) {
24             addBrackets(str + ")", leftB, rightB + 1, n);
25         }
26     }
27 }
28 public class GenerateParentheses {
29     public static void main(String args[]){
30         solution output = new solution();
31         List<String> out = output.generateParenthesis(3);
32         System.out.println(out.size());
33         for (int i = 0; i < out.size(); i++) {
34             System.out.println(out.get(i));
35         }
36     }
37 }

 

目录
相关文章
ValueError: not enough values to unpack (expected 3, got 2)
这个错误通常是因为在解包(unpacking)元组(tuple)时,元组中的元素数量与期望不符,导致无法将所有元素正确解包。 例如,在以下代码中,元组中只有两个元素,但我们尝试将其解包为三个变量:
659 0
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
84 0
LeetCode 241. Different Ways to Add Parentheses
成功解决ValueError: numpy.ufunc size changed, may indicate binary incompatibility. Expected 216 from C h
成功解决ValueError: numpy.ufunc size changed, may indicate binary incompatibility. Expected 216 from C h
成功解决ValueError: numpy.ufunc size changed, may indicate binary incompatibility. Expected 216 from C h
|
Python
SyntaxError: Missing parentheses in call to 'print'
SyntaxError: Missing parentheses in call to 'print'
159 0
成功解决KeyError: “Passing list-likes to .loc or [] with any missing labels is no longer supported. The
成功解决KeyError: “Passing list-likes to .loc or [] with any missing labels is no longer supported. The
成功解决ValueError: not enough values to unpack (expected 2, got 1)
成功解决ValueError: not enough values to unpack (expected 2, got 1)
成功解决ValueError: not enough values to unpack (expected 2, got 1)
|
机器学习/深度学习 人工智能
|
C++ 机器学习/深度学习