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: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/generate-parentheses 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.ArrayList; import java.util.List; /* * 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: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/generate-parentheses 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Lc22 { /* * * 回溯,有几分搜索算法的味道 * * 建议debug item这个变量 观察他的变化 * * 這是基本規則 * * * 左括号个数必须大于右括号的放置个数 才能继续放右括号 * * * 左括号的个数小于n 才能继续放左括号 * * * 左括号和右括号满足上述条件的前提下都为n个,添加这个答案 */ public static void generate(String item, int left, int right, List res) { if (left == 0 && right == 0) { res.add(item); return; } if (left > 0) { generate(item + "(", left - 1, right, res); } if (left < right) { generate(item + ")", left, right - 1, res); } } public static List<String> generateParenthesis(int n) { List res = new ArrayList<>(); generate("", n, n, res); return res; } public static void main(String[] args) { System.out.println(generateParenthesis(2)); } }