題目
在第一行我們寫上一個 0。接下來的每一行,將前一行中的0替換爲01,1替換爲10。
給定行數 N 和序數 K,返回第 N 行中第 K個字符。(K從1開始)
例子:
輸入: N = 1, K = 1
輸出: 0
輸入: N = 2, K = 1
輸出: 0
輸入: N = 2, K = 2
輸出: 1
輸入: N = 4, K = 5
輸出: 1
解釋:
第一行: 0
第二行: 01
第三行: 0110
第四行: 01101001
注意:
N 的範圍 [1, 30].
K 的範圍 [1, 2^(N-1)].
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/k-th-symbol-in-grammar
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
解題思路
遞歸
問題的關鍵:Try to represent the current (N, K) in terms of some (N-1, prevK). What is prevK ?
提交答案
class Solution {
public int kthGrammar(int N, int K) {
if (N == 1) return 0;
int res = kthGrammar(N-1, (K+1)/2);
if(res == 0){
return (1 - K%2);
}else{
return K%2;
}
}
}