1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| class Solution { public List<String> generateParenthesis(int n) { List<String> result = new ArrayList<String>(); generateAll(new char[2*n], 0, result); return result; }
public void generateAll(char[] current, int pos, List<String> result) { if(pos == current.length){ if(valid(current)){ result.add(new String(current)); } } else{ current[pos] = '('; generateAll(current, pos + 1, result); current[pos] = ')'; generateAll(current, pos + 1, result); } }
public boolean valid(char[] current){ int balance = 0; for(char c : current){ if(c == '('){ balance++; }else{ balance--; } if(balance < 0){ return false; } } return balance == 0; } }
class Solution { List<String> result = new ArrayList<String>(); public List<String> generateParenthesis(int n) { dfs(n, 0, 0, ""); return result; }
public void dfs(int n, int lc, int rc, String str){ if(lc == n && rc == n){ result.add(str); } else{ if(lc < n) dfs(n, lc+1, rc, str+"("); if(rc < n && lc > rc) dfs(n, lc, rc+1, str+")");
} } }
|