美文网首页Leetcode
Leetcode 89. Gray Code

Leetcode 89. Gray Code

作者: SnailTyan | 来源:发表于2018-10-24 17:57 被阅读1次

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Gray Code

2. Solution

  • Version 1
class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> result;
        bitset<32> code;
        traverse(result, code, n - 1);
        return result;
    }

private:
    void traverse(vector<int>& result, bitset<32>& code, int pos) {
        if(pos < 0) {
            int value = code.to_ulong();
            result.push_back(value);
            return;
        }
        traverse(result, code, pos - 1);
        code.flip(pos);
        traverse(result, code, pos - 1);
    }
};
  • Version 2
class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> result;
        int code = 0;
        traverse(result, code, n - 1);
        return result;
    }

private:
    void traverse(vector<int>& result, int& code, int pos) {
        if(pos < 0) {
            result.push_back(code);
            return;
        }
        traverse(result, code, pos - 1);
        code ^= (1 << pos);
        traverse(result, code, pos - 1);
    }
};

Reference

  1. https://leetcode.com/problems/gray-code/description/

相关文章

  • Leetcode 89. Gray Code

    文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. S...

  • Leetcode 89. Gray Code

    The gray code is a binary numeral system where two succes...

  • LeetCode89 Gray Code

    LeetCode89 Gray Code The gray code is a binary numeral sy...

  • LeetCode笔记:89. Gray Code

    问题: The gray code is a binary numeral system where two su...

  • [Math]89. Gray Code

    分类:Math 时间复杂度: O(n) 空间复杂度: O(n) 89. Gray Code The gray co...

  • 89. Gray Code

    这题做的很虚, 嗯,居然过了 题目中的一种做法的复现: 打死我吧,打死我我可能会想出来这种办法

  • 89. Gray Code

    题目描述:给非负整数 n 表示二进制位数,输出所有的 n 位格雷码,以0开始。 分析:时间复杂度O(2^n),空间...

  • 89. Gray Code

  • 89. Gray Code

    i = i^(i/2) 别问我咋的出来的, 不知道。。。

  • 89. Gray Code

    The gray code is a binary numeral system where two succes...

网友评论

    本文标题:Leetcode 89. Gray Code

    本文链接:https://www.haomeiwen.com/subject/erpxtqtx.html