查看: 1599| 回复: 1
跳转到指定楼层
上一主题 下一主题
收起左侧

[Leetcode] Generate Parentheses的一个小问题

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 nibuxing 于 2014-10-31 08:04 编辑

题目是:

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:

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


这段是可以通过的代码,但我如果把String换成StringBuffer就会超时,是为啥?
  1. import java.util.ArrayList;
  2. public class Solution {
  3.     public ArrayList<String> generateParenthesis(int n) {
  4.         ArrayList<String> result = new ArrayList<String>();
  5.         if(n <= 0) return result;
  6.         generateParen(result, n, n, "");
  7.         return result;
  8.     }
  9.     private void generateParen(ArrayList<String> result, int leftRemain, int rightRemain, String sb){
  10.         if(leftRemain < 0 || rightRemain < 0 || leftRemain > rightRemain) return;
  11.         if(leftRemain == 0 && rightRemain == 0){
  12.             result.add(sb);
  13.         } else {
  14.             generateParen(result, leftRemain - 1, rightRemain, sb+"(");
  15.             generateParen(result, leftRemain, rightRemain - 1, sb+")");
  16.         }
  17.     }
  18. }
复制代码
这是换成StringBuffer的代码
  1. public ArrayList<String> generateParenthesis(int n) {
  2.         ArrayList<String> result = new ArrayList<String>();
  3.         if(n <= 0) return result;
  4.         generateParen(result, n, n, new StringBuffer());
  5.         return result;
  6.     }
  7.     private void generateParen(ArrayList<String> result, int leftRemain, int rightRemain, StringBuffer sb){
  8.         if(leftRemain < 0 || rightRemain < 0 || leftRemain > rightRemain) return;
  9.         if(leftRemain == 0 && rightRemain == 0){
  10.             result.add(sb.toString());
  11.         } else {
  12.             generateParen(result, leftRemain - 1, rightRemain, sb.append("("));
  13.             generateParen(result, leftRemain, rightRemain - 1, sb.append(")"));
  14.         }
  15.     }
复制代码

上一篇:Leetcode C++
下一篇:位操作的题也是醉了
🔗
sxh53 2014-11-18 01:48:39 | 只看该作者
全局:
StringBuffer is mutable.
So everytime you do line 12 and when it comes back to execute line 13, 'sb' is changed with an additional '(', which may cause the problem. You may need to delete that '(' in your sb before you execute Line 13.
On the contrary String is immutatble. So sb in the first program would always stay the same.
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表