您的位置:首页 > 其它

[LeetCode]22. Generate Parentheses

2016-04-07 15:48 441 查看

Problem Description

[]https://leetcode.com/problems/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:

“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

思路

递归

Code

package q022;

import java.util.ArrayList;
import java.util.List;

public class Solution {

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

public void helper(List<String> ans, String tmp, int n, int m) {
if (n == 0 && m == 0)
ans.add(new String(tmp)
4000
);
if (n >= 1)
helper(ans, tmp + "(", n - 1, m);
if (m >= 1 && n < m)
helper(ans, tmp + ")", n, m - 1);

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: