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, the1-strow is0, the2-ndrow is01, and the3-rdrow is0110.
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];
}
题解的递归:
为奇数就和 处数字相同,偶数就取反。
int kthGrammar(int n, int k){
if (n == 1) return 0;
return (k & 1) ^ 1 ^ kthGrammar(n - 1, (k + 1) / 2);
}