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 對括號邮辽,請寫一個函數(shù)以將其生成新的括號組合,并返回所有組合結(jié)果空另。
分析
深度優(yōu)先搜索旭斥,關(guān)鍵是找限制條件,右括號的數(shù)量不能比左括號數(shù)量多止喷。
代碼
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
if(n <= 0)
return res;
String parent = "";
dfs(res, "",n , n);
return res;
}
private void dfs(List<String> res, String parent, int left, int right) {
if(left == 0 && right == 0) {
res.add(parent);
return;
}
if(left > 0) {
dfs(res, parent+"(",left-1,right);
}
if(right > 0 && right > left) {
dfs(res, parent + ")",left,right-1);
}
}
}