文章 224
评论 6
浏览 200764
parentheses - 22. Generate Parentheses

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);
        }
    }
}

标题:parentheses - 22. Generate Parentheses
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/07/22/1563755071620.html

Nothing just happens, it's all part of a plan.

取消