Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions arai60/kth_symbol_in_grammar/phase1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
moves = deque([]) # 0: move left 1: move right
Copy link

Choose a reason for hiding this comment

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

k を 1-indexed から 0-indexed に変換してから処理すると、コードが少しシンプルになると思いました。

# store the order from the leaf
for i in range(n-1):
if (k - 1) % 2 == 0:
moves.appendleft(0)
else:
moves.appendleft(1)
k = (k - 1) // 2 # 0-indexed
k += 1 # 1-indexed
kth_symbol = 0
for move in moves:
# move 0 kth_symbol 0 -> 0
# move 1 kth_symbol 0 -> 1
# move 0 kth_symbol 1 -> 1
# move 1 kth_symbol 1 -> 0
kth_symbol = kth_symbol ^ move

return kth_symbol
50 changes: 50 additions & 0 deletions arai60/kth_symbol_in_grammar/phase2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""
Reference:
Mike0121: https://github.com/Mike0121/LeetCode/pull/18/files
再帰で書く書き方, 僕がphase1で書いたやり方は移動順を取り出してきて根から辿る方法だが, こっちだと明示的にfor文を書かなくてもかける

Exzrgs: https://github.com/Exzrgs/LeetCode/pull/12/files
shining-ai: https://github.com/shining-ai/leetcode/pull/46/files
kを1で表した時の数の1の数と反転回数に注目, bitcountを用いて解く
hayashi-ay: https://github.com/hayashi-ay/leetcode/pull/46/files
親を表す単語が問題文にないことに注意して命名を行う
"""

# k = (k-1) // 2 + 1がk = (k+1) // 2でまとめられることに気づきまとめる
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
moves = deque([]) # 0: move left 1: move right
# store the order from the leaf
for i in range(n-1):

Choose a reason for hiding this comment

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

i使っていないので、for _ in range(n - 1)でいい気がします。

if (k - 1) % 2 == 0:
moves.appendleft(0)
else:
moves.appendleft(1)
k = (k + 1) // 2
kth_symbol = 0
for move in moves:
# move 0 kth_symbol 0 -> 0
# move 1 kth_symbol 0 -> 1
# move 0 kth_symbol 1 -> 1
# move 1 kth_symbol 1 -> 0
kth_symbol = kth_symbol ^ move

return kth_symbol

# 再帰
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if k == 1:
return 0

previous_value = self.kthGrammar(n - 1, (k + 1) // 2)

if k % 2 == 0:
return 1 - previous_value
else:
return previous_value

# bit count
class Solution:
def kthGrammar(self, n: int, k: int) -> int:
return (k - 1).bit_count() % 2
12 changes: 12 additions & 0 deletions arai60/kth_symbol_in_grammar/phase3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# 再帰で解く方法を選択

class Solution:
def kthGrammar(self, n: int, k: int) -> int:
if k == 1:
return 0

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