Tuesday, September 15, 2015

Generate Parentheses | Leetcode

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: Maintain a running string and list of answers. Keep count of the number of open and close parentheses. If the number of open parentheses has not reached the target number n yet, then we can add an open parentheses. If the number of close parentheses is still less than the number of open parentheses, then we can add a close parentheses. When we reach the target (closeCount == n), then add the current string to the answer.
public class Solution {
    private StringBuilder sb = new StringBuilder();
    private List<String> answer = new ArrayList<>();
    
    public List<String> generateParenthesis(int n) {
        addParens(0, 0, n);
        return answer;
    }
    
    private void addParens(int openCount, int closeCount, int n) {
        if (closeCount == n) {
            answer.add(sb.toString());
            return;
        }
        if (openCount < n) {
            sb.append('(');
            addParens(openCount + 1, closeCount, n);
            sb.setLength(sb.length() - 1);
        }
        if (openCount > closeCount) {
            sb.append(')');
            addParens(openCount, closeCount + 1, n);
            sb.setLength(sb.length() - 1);
        }
    }
}

No comments: