1.题目描述
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:
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
2.Solutions
1 | /** |
I would like to share my understanding about this algorithm. Hope will make people easier to understand the beauty of this code. Chip in your ideas if I am wrong.
The goal is to print a string of “(“ ,”)” in certain order. The length of string is 2n. The constraints(限制) are that “(“s need to match “)”s.
Without constraints, we just simply print out “(“ or “)” until length hits n. So the base case will be length ==2n, recursive(递归) case is print out “(“ and “)”. The code will look like
1 | //base case |
Let’s add in constraints now. We need to interpret the meanings of constraints.
First, the first character should be “(“.
Second, at each step, you can either print “(“ or “)”, but print “)” only when there are more “(“s than “)”s.
Stop printing out “(“ when the number of “(“ s hit n. The first actually merges into the second condition.
The code will be:
1 | //base case |
程序运行图: