Leetcode-Generate Parentheses

本文介绍了一个递归算法,用于生成所有合法的n对括号组合。通过递归地添加左括号和右括号,并确保右括号的数量不超过左括号数量的方法,实现了有效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

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

Have you met this question in a real interview?
 
Analysis:
We define the subproblem as if we now have n left parenthese and m right parenthese, how to generate all legal output.
1. We can always put a left parenthese, and then solve the subproblem with n-1 and m.
2. We can put a right parenthese here only if m>n, otherwise, the output violate the mathcing rule. If we put a right parenthese, we then solve the subproblem with n and m-1.
 
Solution:
 1 public class Solution {
 2     public List<String> generateParenthesis(int n) {
 3         List<String> resSet = new ArrayList<String>();
 4         if (n==0) return resSet;
 5         String curStr = "";
 6         parenthesisRecur(curStr,n,n,resSet);
 7         return resSet;
 8     }
 9 
10     public void parenthesisRecur(String curStr, int n, int m, List<String> resSet){
11         if (n==0 && m==0){
12             resSet.add(curStr);
13             return;
14         }
15 
16         if (n>0){
17             curStr = curStr+"(";
18             parenthesisRecur(curStr,n-1,m,resSet);
19             curStr = curStr.substring(0,curStr.length()-1);
20         }
21 
22         if (m>n){
23             curStr=curStr+")";
24             parenthesisRecur(curStr,n,m-1,resSet);
25             curStr = curStr.substring(0,curStr.length()-1);
26         }
27 
28     }
29 }

 

转载于:https://www.cnblogs.com/lishiblog/p/4111924.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值