[leetcode]K-th Symbol in Grammar
鏈接:https://leetcode.com/problems/reorganize-string/description/
Question
On the first row, we write a 0
. 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
.
Given row N
and index K
, return the K
-th indexed symbol in row N
. (The values of K
are 1-indexed.) (1 indexed).
Example 1
Input: N = 1, K = 1
Output: 0
Input: N = 2, K = 1
Output: 0
Input: N = 2, K = 2
Output: 1
Input: N = 4, K = 5
Output: 1
Explanation:
row 1: 0
row 2: 01
row 3: 0110
row 4: 01101001
N
will be an integer in the range[1, 30]
.K
will be an integer in the range[1, 2^(N-1)]
.
Solution
class Solution {
public:
int dfs(int N, int K) {
if (N == 1 && K == 1) return 0;
if (K <= (1 << (N-2))) {
return dfs(N-1, K);
} else { // 由於後一半是前一半的補,所以可以直接在前面加個負號就可以了
return !dfs(N-1, K-(1 << (N-2)));
}
}
int kthGrammar(int N, int K) {
return dfs(N, K);
}
};
思路:這道題相當機智,利用的是前一半字符串和後一半字符串是互補的特點進行判斷。如果是在前半段相當於dfs(N-1, K),而如果是在後半段,則是dfs(N-1, K-(1 << (N-2)))的負。