编程语言
首页 > 编程语言> > 算法:22. Generate Parentheses生成配对括号

算法: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 + ")");
        }
    }
}

标签:right,helper,22,int,List,list,Parentheses,Generate,left
来源: https://blog.csdn.net/zgpeace/article/details/118105243