classSolution{ List<String> res = new LinkedList<>(); int n; public List<String> generateParenthesis(int n){ this.n = n; backtrack(new StringBuilder(), n, n); return res; }
publicvoidbacktrack(StringBuilder path, int left, int right){ //结束条件 if(left == 0 && right == 0){ res.add(new String(path)); return; } //选择1:使用左括号 if(left > 0){ path.append('('); backtrack(path, left - 1, right); path.deleteCharAt(path.length() - 1); } //选择2:使用右括号 if(left < right && right > 0){ path.append(')'); backtrack(path, left, right - 1); path.deleteCharAt(path.length() - 1); } } }