Friday, November 27, 2015

[leetcode]Generate Parentheses

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
    public List<String> generateParenthesis(int n) {
        if (n < 0) return result;
        rec(n, 0, "");
        return result;
    }
    
    List<String> result = new ArrayList<String>();
    private void rec(int available, int unmatch, String fromUpper){
        if (available == 0){
            for (int i = 0; i < unmatch; i++) fromUpper += ")";
            result.add(fromUpper);
            return;
        }
        String addOn = "";
        for (int i = 0; i <= unmatch; i++){
            rec(available-1, unmatch-i+1, fromUpper+addOn+"(");
            addOn += ")";
        }
    }
}

No comments:

Post a Comment