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

2021/6/22 14:27:08

本文主要是介绍算法: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 + ")");
        }
    }
}


这篇关于算法:22. Generate Parentheses生成配对括号的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程