Skip to content

22. Generate Parentheses #17

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

22. Generate Parentheses #17

wants to merge 1 commit into from

Conversation

katsukii
Copy link
Owner

if (left > 0) {
s.append("(");
func(list, s, left - 1, right);
s.setLength(s.length()-1);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

- の両側にスペースを空けることをお勧めいたします。

また、フォーマッターの導入をお勧めいたします。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ご指摘ありがとうございます。見落としてました。

public class Solution {
public static List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<>();
StringBuilder s = new StringBuilder();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

知識を確認するために質問させてください。 StringBuilder と StringBuffer の違いは判りますか?また、今回はどちらを使うのが適切だと思いますか?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

そもそも StringBuffer 自体を使ったことがなく知りませんでした。調査の上で以下のように理解しました。

StringBuilder はシングルスレッド向けのクラスであり、一方で StringBuffer はマルチスレッド環境でも利用できるスレッドセーフなクラスです(ただし同期処理のコストがあるため、StringBuilder よりも処理速度は遅くなります)。
今回はシングルスレッドなのでStringBuilder を使うのが適切という理解です。

時間計算量: O(4^n)
空間計算量: O(4^n)

* 最初、四重ループだから素直にO(n^4)かなと考えたが、違うらしい
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

自分で作ったテーブルの回数だけ回っているので、そうはなりません。

カタラン数は、ソフトウェアエンジニアの常識からは外れていると思います。
このあたりから辿ってもらえれば。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.lqk42foli42r

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。
O(4^n / (sqrt(n) * n)) なのですね。理解に時間がかかりそうなので、このような考え方もあるという程度に頭に留めておこうと思います。

}
```

* 感想: 四重ループは可読性と処理の重さの観点から引数が大きい場合はあまり現実的な解ではなさそう
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

処理が重いのはそもそもの問題の性質によるところがありますね。
四重ループになって読みにくい事自体は、書き方次第でやりようがありそうです。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants