LeetCode每日一题: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:
"((()))", "(()())", "(())()", "()(())", "()()()"

问题分析

遇到要列出所有情况的问题直接使用递归,用left和right分别表示左右括号的个数,直接递归即可。

代码实现

public ArrayList generateParenthesis(int n) {
        ArrayList result = new ArrayList<>();
        printParenthesis(n, 0, 0, "", result);
        return result;
    }

    private void printParenthesis(int n, int left, int right, String s, ArrayList result) {
        if (right == n) result.add(s);
        if (left < n) printParenthesis(n, left + 1, right, s + "(", result);
        if (left > right) printParenthesis(n, left, right + 1, s + ")", result);
    }

你可能感兴趣的:(LeetCode每日一题:generate parentheses)