leetcode: 22. Generate Parentheses

Difficulty

Medium

Description

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:

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

Solution

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList();
		backtrack(ans, "", 0, 0, n);
		return ans;
    }

	public void backtrack(List<String> ans, String cur, int open, int close, int n) {
		if (cur.length() == 2 * n)
		{
			ans.add(cur);
			return;
		}

		if (open < n)
		{
			backtrack(ans, cur + "(", open + 1, close, n);
		}

		if (open > close)
		{
			backtrack(ans, cur + ")", open, close + 1, n);
		}
	}
}

猜你喜欢

转载自blog.csdn.net/baidu_25104885/article/details/86674543