[LeetCode]22. Generate Parentheses

来源:互联网 发布:ubuntu arm linux gcc 编辑:程序博客网 时间:2024/04/30 23:55

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));        if (n >= 1)            helper(ans, tmp + "(", n - 1, m);        if (m >= 1 && n < m)            helper(ans, tmp + ")", n, m - 1);    }}
0 0
原创粉丝点击