parentheses - 22. Generate Parentheses

11

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