Wednesday, January 7, 2015

LeetCode 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:
"((()))", "(()())", "(())()", "()(())", "()()()"
public class Solution {
    public List<String> generateParenthesis(int n)
    {
        // Adopt depth first search
        List<String> result = new LinkedList<>();
        String item = "";
        
        if (n <= 0)
            return result;  
            
        dfs(result, item, n, n);
        
        return result;  
    }  
    
    // left - remaining number of "("; right - remaining number of ")"  
    public void dfs(List<String> result, String item, int left, int right)
    {
        // In this case, there isn't enough ")" after "(", e.g., ")(".
        if(left > right)
            return;
            
        if (left == 0 && right == 0)
        {  
            result.add(item);
            return;  
        }
        
        if (left > 0) 
            dfs(result, item+'(', left-1, right);
            
        if (right > 0) 
            dfs(result, item+')', left, right-1);  
    }
}

No comments:

Post a Comment