K-th Symbol in Grammar

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/perdon123123/article/details/81591761

[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)))的负。

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页