Skip to content

779. K-th Symbol in Grammar#35

Open
ryosuketc wants to merge 1 commit intomainfrom
779_k_th_symbol_in_grammar
Open

779. K-th Symbol in Grammar#35
ryosuketc wants to merge 1 commit intomainfrom
779_k_th_symbol_in_grammar

Conversation

@ryosuketc
Copy link
Copy Markdown
Owner

@@ -0,0 +1,14 @@
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
def kth_grammer_helper(n, k):
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

引数が同じなのでインナー関数を定義する必要はないと思います。

* recursion の問題だなーとは思いながら考えたけど明確な解法思いつかず。
* とりあえず愚直な解法を実装してみたけど memory limit exceeded
* n が 30 までということは、2^30 文字の文字列を保存することになる。
* `sys.getsizeof("a") -> 50` (bytes) とかなので、途方もないサイズになる
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

文字列本体のメモリ + Python のオブジェクトに必要なメモリ + str に必要なメモリで 50 バイトとなっているのだと思います。文字一文字あたりは 1 バイトのようです。

>>> import sys
>>> sys.getsizeof("a")
50
>>> sys.getsizeof("aa")
51
>>> sys.getsizeof("aaa")
52
>>> sys.getsizeof("aaaa")
53

if n == 1:
return 0

if k % 2:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

否定してから int にキャストしているのが、やや分かりずらく感じました。引き算のほうがシンプルだと思いました。

if k % 2:
    return self.kthGrammar(n - 1, (k + 1) // 2)
else:
    return 1 - self.kthGrammar(n - 1, (k + 1) // 2)

@ryosuketc ryosuketc added the need re-review Review comments are lightly examined and re-review of the problem is needed. label Jul 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

need re-review Review comments are lightly examined and re-review of the problem is needed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants