Leetcode OJ 22 Generate Parentheses [Medium]

本文介绍了一种生成所有合法括号组合的算法,通过递归方式实现,适用于n对括号的所有可能组合。文章提供了完整的Java实现代码及解析。

Leetcode OJ 22 Generate Parentheses [Medium]

题目描述:

Given n pairs of parentheses, write a function togenerate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[

 "((()))",

 "(()())",

 "(())()",

 "()(())",

 "()()()"

]

 

题目理解:

   实现一个函数:给定一个整数n,输出所有n对括号的组合。

测试用例:

    功能测试:输入1、2、3等;

    边界测试:输入0;

    性能测试:输入大整数如1000;

分析:

     1.  在一个排列中(字符串),每一个位置往前,左括号数leftNum大于等于右括号数rightNum;左括号数号数小于等于n;

     2.  可用动态规划(递归)解决该问题:初始leftNum和rightLeft都是0。

     3.  对于每一个排列(字符串),字符串初始是空,如果字符串长度等于2n,则将该字符串输出;

     4.  如果leftNum小于n,则可向字符串中添加‘(’,leftNum加1,继续进行后续添加括号操作,操作相同;

     5.  如果rightNum小于leftNum,则可向字符串中添加‘)’,rightNum加1,继续进行后续添加括号操作,操作相同;

     6.  注意4、5步进行时,保证leftNum、rightNum、字符串s都没有被修改;

     也就是说,正确的是:

if(leftNum < n){
    addParenthesis(result,s+"(",leftNum+1, rightNum,n);
}
if(rightNum < leftNum){
    addParenthesis(result,s+")",leftNum,rightNum+1,n);
}

     错误的是:

if(leftNum < n){
    s += "(";
    leftNum += 1;
    addParenthesis(result,s,leftNum, rightNum,n);
}
if(rightNum < leftNum){
    addParenthesis(result,s+")",leftNum,rightNum+1,n);
}

解答:

package leetcode;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/30.
 */
public class generateParenthesis22 {
    public static void main(String[] args) {
        int n = 10;
        List<String> result = new ArrayList<String>();
        addParenthesis(result,"",0,0,n);
        System.out.println(result);
    }

    public static void addParenthesis(List<String> result, String s, int leftNum, int rightNum, int n) {
        if(s.length() == 2 * n){
            result.add(s);
            return;
        }
        if(leftNum < n){
            addParenthesis(result,s+"(",leftNum+1, rightNum,n);
        }
        if(rightNum < leftNum){
            addParenthesis(result,s+")",leftNum,rightNum+1,n);
        }
    }
}

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值