数字 n
代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3 输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1 输出:["()"]class Solution { public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<>(); StringBuilder path = new StringBuilder(); backtrack(res, path, 0, 0, n); return res; }
private void backtrack(List<String> res, StringBuilder path, int open, int close, int max) { if (path.length() == max * 2) { res.add(path.toString()); return; } if (open < max) { backtrack(res, path.append("("), open + 1, close, max); path.deleteCharAt(path.length()-1); } if (close < open) { backtrack(res, path.append(")"), open, close + 1, max); path.deleteCharAt(path.length()-1); } } } 标签:22,backtrack,int,res,力扣,括号,max,path,open From: https://www.cnblogs.com/JavaYuYin/p/18064547