779 K-th Symbol in Grammar
1. Question
On the first row, we write a0
. Now in every subsequent row, we look at the previous row and replace each occurrence of0
with01
, and each occurrence of1
with10
.
Given rowN
and indexK
, return theK
-th indexed symbol in rowN
. (The values ofK
are 1-indexed.) (1 indexed).
Note:
N
will be an integer in the range[1, 30]
.K
will be an integer in the range[1, 2^(N-1)]
.
2. Implementation
(1) Recursion
思路: 可以把这题看成是一个fully binary tree,其中node是0或者1, 如果node是0的话,它的left child是0,right child是1,node是1的话,left child是1, right child是0.要知道第N行,第K列的数是1还是0,我们要知道第N - 1行, 第 (K + 1)/2列 ((K + 1)/ 2可以得到当前node的parent node)的数是什么,根据这个再判断K的奇偶性得到结果
3. Time & Space Complexity
Recursion: 时间复杂度O(N), 空间复杂度O(N), 递归的深度是N
Last updated