LeetCode: Generate Parentheses
问题描述
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example1
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example2
Input: n = 1
Output: ["()"]
方法思路
对于这种按顺序生成字符串并且每一个位置的值都有两种选择的情况,最开始让我想到的解决方法是在设置一定条件的情况下(在没有到达字符串规定长度的情况’(‘的数量必须多于’)’;只能存在n个’(’)通过二叉树进行解决,以 n = 3 为例,生成的二叉树如下图:
在Java中,可能通过嵌套函数的方式来实现以上的思路,函数每执行一次都会有添加’(‘和添加’)‘两种情况,在对两种情况以及何时结束嵌套函数的运行进行限定。
- 结束情况: 数组长度达到了 2n;
- 添加’(‘的情况: 只需要满足’('的数量小于n;
- 添加’)‘的情况: 因为每个’)‘都必须有’)‘与之对应,所以’)‘的数量小于’(‘的数量的情况下可以添加’)’。
代码如下(示例):
class Solution {
public List<String> generateParenthesis(int n) {
ArrayList<String> res = new ArrayList<>();
gen("(",1,0,res,n);
return res;
}
void gen(String input, int l, int r, ArrayList<String> res, int n){
//如果字符串的长度达到了2n,将字符串添加到List并结束循环
if(input.length() == 2*n){
res.add(input);
return;
}
//'('的数量小于n的情况下,可以添加'('
if(l<n) gen(input+'(',l+1,r,res,n);
//')'的数量小于'('的数量的情况下,可以添加')'
if(r<l) gen(input+')',l,r+1,res,n);
}
}