779. K-th Symbol in Grammar
阿新 • • 發佈:2018-11-27
public ota reverse color class div rev AMM urn
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) returnhelper(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