779. K-th Symbol in Grammar

Posted jtechroad

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了779. K-th Symbol in Grammar相关的知识,希望对你有一定的参考价值。

class Solution {
public:
    int kthGrammar(int N, int K) {
        return helper(N, K, false);
    }
    int helper(int n, int k, bool reverse) {
        if (n == 1) return reverse;
        int total = 1 << (n-1);
        int half = total >> 1;
        if (k <= half)
            return helper(n-1, k, reverse);
        else
            return helper(n-1, k-half, !reverse);
    }
};

/*
lvl1: 0
lvl2: 0 1
lvl3: 0 1 1 0
lvl4: 0 1 1 0   1 0 0 1
lvl5: 0 1 1 0   1 0 0 1   1 0 0 1   0 1 1 0
      0 1 1 0   1 0 0 1   1 0 0 1   0 1 1 0   1 0 0 1   0 1 1 0   0 1 1 0   1 0 0 1
      */

 

以上是关于779. K-th Symbol in Grammar的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode-779-K-th Symbol in Grammar]

leetcode 779. K-th Symbol in Grammar ---回溯

K-th Symbol in Grammar

[LeetCode] K-th Symbol in Grammar 语法中的第K个符号

Leetcode: K-th Smallest in Lexicographical Order

[LeetCode] K-th Smallest in Lexicographical Order 字典顺序的第K小数字