Skip to content

Latest commit

 

History

History
40 lines (35 loc) · 824 Bytes

22.md

File metadata and controls

40 lines (35 loc) · 824 Bytes

22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

####Analysis & Solution

 public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList();
        dfs(res, n, n, "");
        return res;
    }
    void dfs(List<String> res, int left, int right, String temp){
        if(left > right){
            return;
        }
        if(left == 0 && right == 0){
            res.add(temp);
            return;
        }
        if(left > 0){
            dfs(res, left - 1, right,  temp + "(");
        }
        if(right > 0){
            dfs(res, left, right - 1, temp + ")");
        }
    }