parentheses - 22. Generate Parentheses

时间:2022-07-25
本文章向大家介绍parentheses - 22. Generate Parentheses,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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:

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

思路:

题目意思是给一个整形数字,返回合法左右括号这种组合的所有组合,典型的使用回溯法来做。

代码:

java:

class Solution {

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<String>();
        backtrack(res, "", 0, 0, n);
        return res;
    }
    
    private void backtrack(List<String> res, String s, int left, int right, int max) {
        if (s.length() == max *2) {
            res.add(s);
            return;
        }
        
        if (left < max) {
            backtrack(res, s + "(", left + 1, right, max);
        }
        
        if (right < left) {
            backtrack(res, s + ")", left, right + 1, max);
        }
    }
}