20221020 - 779. K-th Symbol in Grammar 第K个语法符号(递归)

100 阅读1分钟

We build a table of n rows (1-indexed). We start by writing 0 in the 1-st row. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.

  • For example, for n = 3, the 1-st row is 0, the 2-nd row is 01, and the 3-rd row is 0110.

Given two integer n and k, return the k-th (1-indexed) symbol in the n-th row of a table of n rows.

Example 1

Input: n = 1, k = 1
Output: 0
Explanation: 
row 1: 0

Example 2

Input: n = 2, k = 1
Output: 0
Explanation: 
row 1: 0
row 2: 01

Example 3

Input: n = 2, k = 2
Output: 1
Explanation: 
row 1: 0
row 2: 01

Constraints

  • 1 <= n <= 30
  • 1 <= k <= 2^(n - 1)

Solution

自己写的分治递归生成序列,在最后一个用例超时:

void generate(int *t, int l, int len)
{
    if (len == 1)
        return;
    if (len == 2) {
        t[l + 1] = !t[l];
        return;
    }
    t[l + len / 2] = !t[l];
    generate(t, l, len / 2);
    generate(t, l + len / 2, len / 2);
}

int kthGrammar(int n, int k){
    int i, j, len;
    len = (1 << (n - 1)) + 1;
    int *t = (int*)malloc(sizeof(int) * len);
    t[1] = 0;
    generate(t, 1, len - 1);
    return t[k];
}

题解的递归:

Pasted image 20221020120506.png

xx 为奇数就和 x+12\lfloor \cfrac{x+1}{2} \rfloor 处数字相同,偶数就取反。

int kthGrammar(int n, int k){
    if (n == 1) return 0;
    return (k & 1) ^ 1 ^ kthGrammar(n - 1, (k + 1) / 2);
}

题目链接:779. 第K个语法符号 - 力扣(LeetCode)