题目:
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
解题:
class Solution { public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<>(); return st(n,n,res,""); } public static List<String> st(int l,int r, List<String> res, String stemp){ if(l == 0 && r == 0) res.add(stemp); if(l > 0) { st(l - 1, r, res, stemp + "("); } if( r > 0 && r > l) // ) 必须匹配之前的 ( st( l, r-1, res, stemp + ")"); return res; } }