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:

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

思路: 递归, 左括号个数用left表示, 右括号用right表示;
递归终止条件: left == n && right == n
递归过程: 先加入左括号, 条件为left right)

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        if (n <= 0) return res;
        helper("", res, 0, 0, n);
        return res;
    }

    public void helper(String tmp, List<String> res, int left, int right, int n) {
        if (left == n && right == n) {
            res.add(tmp);
            return;
        }
        if (left < n) {
            helper(tmp + "(", res, left + 1, right, n);
        }
        if (right < left) {
            helper(tmp + ")", res, left, right + 1, n);
        }
    }
}

Follow up: 缩进输出
借鉴解法: 替换 left== n && right == n

int level = 0;
for(int i = 0; i < tmp.length(); i++){
    if(tmp.charAt(i) == '{'){
        for(int k = 0; k < level; k++){
            System.out.print('\t');
        }
        System.out.println('{');
        level++;
    } else {
        level--;
        for(int k = 0; k < level; k++){
            System.out.print('\t');
        }
        System.out.println('}');
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s