/* * @lc app=leetcode id=22 lang=java * * [22] Generate Parentheses */ // @lc code=start class Solution { public List generateParenthesis(int n) { List r = new ArrayList(); dfsGenParenthesis(r, "", 0, 0, n); return r; } private void dfsGenParenthesis(List r, String s, int i, int k, int n) { if(i == n && k == 0) { r.add(s); return; } else if(i > n) { return; } if(i < n) { String t = s + "("; dfsGenParenthesis(r, t, i+1, k+1, n); } if(k > 0) { String t = s + ")"; dfsGenParenthesis(r, t, i, k-1, n); } } } // @lc code=end