leetcode--Generate Parentheses

来源:互联网 发布:北川景子 知乎 编辑:程序博客网 时间:2024/05/21 17:14

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

public class Solution {    public List<String> generateParenthesis(int n) {List<String> result = new ArrayList<String>();solve(0, 0, n, result, "");System.out.println(result);return result;    }void solve(int left,int right,int n,List<String> result,String str){if(left<right) return;//left括号数目一定要比右边多if(left==n && right==n){//如果左右括号数目相等则添加到listresult.add(str);return;}if(left==n){//左括号已满,只能添加右括号solve(left, right+1, n, result, str+")");return;}solve(left+1, right, n, result, str+"(");//继续添加左括号solve(left, right+1, n, result, str+")");//继续添加右括号}}


0 0
原创粉丝点击