算法:22. Generate Parentheses生成配对括号

22. Generate Parentheses

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

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

Input: n = 1
Output: ["()"]

Constraints:

1 <= n <= 8

回溯算法

回溯算法,可以用排列的形式证明是不可重复的。

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<String>();
        helper(list, n, n, "");
        
        return list;
    }
    
    public void helper(List<String> list, int left, int right, String s) {
        if (left == 0 && right == 0) {
            list.add(s);
            return;
        }
        if (left > 0) {
            helper(list, left - 1, right, s + "(");
        } 
        if (right > left) {
            helper(list, left, right - 1, s + ")");
        }
    }
}
上一篇:LeetCode-020-有效的括号


下一篇:编译器实现之旅——第四章 实现词法分析器