推荐:数据科学课程和书籍清单以及培训讲座


一亩三分地论坛

 找回密码
 获取更多干活,快来注册

一亩三分地官方iOS手机应用下载
查看: 586|回复: 1
收起左侧

[Leetcode] Generate Parentheses的一个小问题

[复制链接] |试试Instant~ |关注本帖
nibuxing 发表于 2014-10-31 05:00:31 | 显示全部楼层 |阅读模式

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

您需要 登录 才可以下载或查看,没有帐号?获取更多干活,快来注册

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.     }
复制代码
sxh53 发表于 2014-11-18 01:48:39 | 显示全部楼层
关注一亩三分地公众号:
Warald_一亩三分地
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.
回复 支持 反对

使用道具 举报

本版积分规则

关闭

一亩三分地推荐上一条 /5 下一条

手机版|小黑屋|一亩三分地论坛声明

custom counter

GMT+8, 2017-7-28 12:41

Powered by Discuz! X3

© 2001-2013 Comsenz Inc. Design By HUXTeam

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