Open
Conversation
hroc135
reviewed
Jun 23, 2025
| @@ -0,0 +1,14 @@ | |||
| class Solution: | |||
| def kthGrammar(self, n: int, k: int) -> int: | |||
| def kth_grammer_helper(n, k): | |||
nodchip
reviewed
Jun 24, 2025
| * recursion の問題だなーとは思いながら考えたけど明確な解法思いつかず。 | ||
| * とりあえず愚直な解法を実装してみたけど memory limit exceeded | ||
| * n が 30 までということは、2^30 文字の文字列を保存することになる。 | ||
| * `sys.getsizeof("a") -> 50` (bytes) とかなので、途方もないサイズになる |
There was a problem hiding this comment.
文字列本体のメモリ + 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: |
There was a problem hiding this comment.
否定してから int にキャストしているのが、やや分かりずらく感じました。引き算のほうがシンプルだと思いました。
if k % 2:
return self.kthGrammar(n - 1, (k + 1) // 2)
else:
return 1 - self.kthGrammar(n - 1, (k + 1) // 2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
779. K-th Symbol in Grammar
https://leetcode.com/problems/k-th-symbol-in-grammar/