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:

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

Solution 1: straightforward solution, add “()” to every possible position and use Set to check uniqueness.

public class Solution {
    public List<String> generateParenthesis(int n) {
        if(n==0) return new ArrayList<String>();
        List<String> ans = new ArrayList<>();
        ans.add("()");
        for(int i=1; i<n; i++){
            Set<String> set = new HashSet<>();
            for(String s : ans){
                for(int j=0; j<s.length(); j++){
                    set.add(s.substring(0,j)+"()"+s.substring(j));
                }
            }
            ans = new ArrayList<>(set);
        }
        return ans;
    }
}

Solution 2: recursive.

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        helper(ans, "", 0, 0, n);
        return ans;
    }
    public void helper(List<String> list, String s, int l, int r, int n){
        if(r==n){
            list.add(s);
            return;
        }
        if(l<n) helper(list, s+"(", l+1, r, n);
        if(r<l) helper(list, s+")", l, r+1, n);
    }
}
comments powered by Disqus