文章--LeetCode算法--GenerateParentheses
GenerateParentheses
问题描述
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:
[ "((()))",
"(()())",
"(())()",
"()(())",
"()()()"]
实现代码
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
backtrack(list, "", 0, 0, n);
return list;
}
public void backtrack(List<String> list, String str, int open, int close, int max) {
if (str.length() == max * 2) {
list.add(str);
return;
}
if (open < max)
backtrack(list, str + "(", open + 1, close, max);
backtrack(list, str + ")", open, close + 1, max);
}
}

浙公网安备 33010602011771号