DEV Community

Takahiro Kudo
Takahiro Kudo

Posted on

LeetCode "K-th Symbol in Grammar"

Recursive, Recursive, Recursive...🤮

Reference
https://leetcode.com/explore/learn/card/recursion-i/253/conclusion/1675/discuss/381460/Go-recursion-with-explanation/352630

class Solution:
    def kthGrammar(self, N: int, K: int) -> int:
        if N == 1:
            return 0
        elif N == 2:
            return 0 if K == 1 else 1

        v = self.kthGrammar(N - 1, (K + 1) // 2)
        if v == 0:
            if K % 2 == 0:
                return 1
            else:
                return 0
        else:
            if K % 2 == 0:
                return 0
            else:
                return 1

Enter fullscreen mode Exit fullscreen mode

Top comments (0)