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 }

 

目录
相关文章
params argument given to the optimizer should be an iterable
params argument given to the optimizer should be an iterable
184 0
params argument given to the optimizer should be an iterable
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
79 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
|
人工智能 C++
Longest Valid Parentheses
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
772 0
Leetcode-Easy 20. Valid Parentheses
Leetcode-Easy 20. Valid Parentheses
106 0
Leetcode-Easy 20. Valid Parentheses
成功解决 ValueError: feature_names mismatch training data did not have the following fields
成功解决 ValueError: feature_names mismatch training data did not have the following fields
|
C++ 机器学习/深度学习
|
机器学习/深度学习
[LeetCode]--22. Generate Parentheses
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: [ "((()))", "(()())", "(())()",
1102 0