Conversation
| def generateParenthesis(self, n: int) -> List[str]: | ||
| valid_parentheses = [] # 有効な答えを格納するコンテナ | ||
| under_processing_parentheses = [("", n, n)] # stack | ||
| while under_processing_parentheses: |
| valid_parentheses = [] # 有効な答えを格納するコンテナ | ||
| under_processing_parentheses = [("", n, n)] # stack | ||
| while under_processing_parentheses: | ||
| current_parentheses, remain_open_bracket_count, remain_close_bracket_count = under_processing_parentheses.pop() |
There was a problem hiding this comment.
まだ閉じてない空きカッコだけ保存したらいいと思います。あとどれだけカッコが必要かは、current_parenthesから計算できます。一般にstateは少ない方がいいです。
名前はnum_unclosed_parenthesesとかどうでしょう。
| valid_parentheses.append(current_parentheses) | ||
| continue | ||
|
|
||
| if 0 < remain_open_bracket_count: |
There was a problem hiding this comment.
変数を比較演算子の左側に置いた方が分かりやすいです。remain_open_bracket_count > 0
There was a problem hiding this comment.
私はこっちのほうが好きですね。>, >= は、私はどちらかというと否定的な意図のときに使っています。
index >= len(array)
など。
There was a problem hiding this comment.
なるほど。
変数を比較演算子の左側に置いた方が分かりやすいです。
Mike0121さんが、リーダブルコードにこのアドバイスがあると言っていたのですが、場合によりけりですかね。
よくよく考えたら、私もr < 0 || NUM_ROWS <= rみたいに書いたりする(小さい順に書きたい)ので、特に決まったルールはなさそうです。
| @@ -0,0 +1,20 @@ | |||
| class Solution: | |||
There was a problem hiding this comment.
ちょっと大雑把な考察になってしまったのですが, 状態をグラフで考えた時, 深さnまでは状態数が各状態ノードから大体2個ずつ伸びるので深さnまでの状態数の合計はΣ_{k}2^k, それ以降は状態数は各状態ノードから1個しか伸びないので終了状態になる深さ2nまでの状態数の合計はn2^nなので, 全てのノードを走査するのにかかる時間計算量がO(n2^n), 今回はDFSを行っているので空間計算量がO(n)でしょうか
There was a problem hiding this comment.
出力サイズはだいたいカタラン数ですね。
https://en.wikipedia.org/wiki/Catalan_number
a(n) ~ 4^n / (sqrt(Pi * n) * (n + 1))
https://oeis.org/A000108
あ、これは知らなくていいと思います。
There was a problem hiding this comment.
カタラン数の予備知識なしなら、大体O(n * 2 ^ n)で抑えられそうという見積もりですかね。高さnのbinary treeのノード数がO(2 ^ n)で、最後にstringを生成でO(n)で、合わせてO(n * 2 ^ n)。
空間計算量も出力を含めないなら、O(n)で合ってると思います。
There was a problem hiding this comment.
はい, 途中で2分しないノードも出てくるのでさらに絞り込めそうではありましたがn2^nという大雑把な評価をしました。空間計算量は計算途中だけ考慮してしまいました
There was a problem hiding this comment.
カタラン数との比較を見たら分かると思うのですが、二分木の高さは n ではなく 2n のほうが近いですね。
あと、本当に大事なのは、計算量の見積もりよりも計算時間の見積もりです。
たとえば、1分以内に計算が終わるのは n がいくつまでかを概算して、実際とすり合わせてみましょう。
| while under_processing_parentheses: | ||
| current_parentheses = under_processing_parentheses.pop() | ||
|
|
||
| if current_parentheses.count("(") == n and current_parentheses.count(")") == n: |
There was a problem hiding this comment.
len(current_parentheses) == 2 * nでできそうです。
問題
https://leetcode.com/problems/generate-parentheses/description/?envType=list&envId=xo2bgr0r