这题使用回溯class Solution { ListString res new ArrayList(); public ListString generateParenthesis(int n) { dfs(, 0, 0, n); return res; } public void dfs(String str, int left, int right, int n) { // 结束条件 if (left n right n) { res.add(str); return; } // 放左括号 if (left n) { dfs(str (, left 1, right, n); } // 放右括号 if (right left) { dfs(str ), left, right 1, n); } } }