LeetCode: Generate Parentheses 解题报告

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:

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

Hide Tags Backtracking String

SOLUTION 1:


我们还是使用九章算法的递归模板。

1. Left代表余下的'('的数目

2. right代表余下的')'的数目

3. 注意right余下的数目要大于left,否则就是非法的,比如,先放一个')'就是非法的。

4. 任何一个小于0,也是错的。

5. 递归的时候,我们只有2种选择,就是选择'('还是选择')'。

6. 递归的时候,一旦在结果的路径上尝试过'('还是选择')',都需要回溯,即是sb.deleteCharAt(sb.length() - 1);

 1 public class Solution {
 2     public List<String> generateParenthesis(int n) {
 3         List<String> ret = new ArrayList<String>();
 4         
 5         if (n == 0) {
 6             return ret;
 7         }
 8         
 9         dfs(n, n, new StringBuilder(), ret);
10         
11         return ret;
12     }
13     
14     // left : the left Parentheses
15     // right : the right Parentheses
16     public void dfs(int left, int right, StringBuilder sb, List<String> ret) {
17         if (left == 0 && right == 0) {
18             ret.add(sb.toString());
19             return;
20         }
21         
22         // left < right means that we have more ( then we can add ).
23         if (left < 0 || right < 0 || left > right) {
24             return;
25         }
26         
27         dfs(left - 1, right, sb.append('('), ret);
28         sb.deleteCharAt(sb.length() - 1);
29         
30         dfs(left, right - 1, sb.append(')'), ret);
31         sb.deleteCharAt(sb.length() - 1);
32     }
33 }
View Code

主页君的GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/GenerateParenthesis.java

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值