Sunday, June 3, 2018

Generate Parenthesis

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

Solution:

public class Solution {
    public List generateParenthesis(int n) {
        List res = new ArrayList();
        if(n == 0) return res;

        helper(res, "", 0, 0, n);
        return res;
    }

    public void helper(List res, String s, int open, int close, int max){
        if(s.length() == max*2){
            res.add(s);
            return;
        }

        if(open < max)
            helper(res, s+"(", open+1, close, max);
        
        if(close < open)
            helper(res, s+")", open, close+1, max);
    }
}

No comments:

Post a Comment

My Journey from a Tier-3 College to Microsoft, Google, and Meta: Lessons Learned

Original post: Link   Time to give back to community. Went through couple of post myself and got inspired and belief that cracking FAANG is ...