zoukankan      html  css  js  c++  java
  • 【leetcode】Gray Code (middle)

    The gray code is a binary numeral system where two successive values differ in only one bit.

    Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

    For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

    00 - 0
    01 - 1
    11 - 3
    10 - 2

    思路: Gray Code的意思就是n位的二进制序列,相邻两个只有一位不同。观察

    000 - 0
    001 - 1
    011 - 3
    010 - 2
    110 - 6
    111 - 7
    101 - 5
    100 - 4

    第0位的序列为 01 10 01 这样不断重复

    第1位的序列为 0011 1100

    第2位的序列为 11110000

    这样我们就找到了规律。

    我最开始是通过判段每次是第几位变化,通过异或得到新值。 每次第k为变化时满足 i = 2k + n*2(k+1)

    vector<int> grayCode(int n) {
            vector<int> ans;
            ans.push_back(0);
            if(n == 0)
                return ans;
    
            for(int i = 1; i < (1 << n); i++)
            {
                int bit_change = 0;
                for(int j = 0; j < n; j++)
                {
                    if(i % (1 << (j + 1)) - (1 << j) == 0)
                    {
                        bit_change = j; break;
                    }
                }
                int cur = (1 << bit_change);
                cur ^= ans.back();
                ans.push_back(cur);
            }
            return ans;
        }

    后来看其他人的发现更简单的方法

    vector<int> grayCode2(int n) {
            vector<int> ans;
            ans.push_back(0);
            if(n == 0)
                return ans;
    
            for(int i = 0; i < n; i++)
            {
                int inc = 1 << i;
                for(int j = ans.size() - 1; j >= 0; j--) //每次等第i - 1位正反序都存完毕时,第i位起始为0的情况也存储完了, 只需存储第i位起始为1并且低位倒序输出
                {
                    ans.push_back(ans[j] + inc);
                }
            }
            return ans;
        }
  • 相关阅读:
    markown 画图
    C++ 结构体指针
    C++指针详解
    C++ 中类对象与类指针的区别
    Java面向对象㈠ -- 封装
    path和classpath
    "System.Web" 中不存在类型或命名空间
    ASP.NET 后台不识别ASPX中的控件
    asp.net中的<%%>形式的详细用法实例讲解
    ASP.NET前台JS与后台CS函数如何互相调用
  • 原文地址:https://www.cnblogs.com/dplearning/p/4208623.html
Copyright © 2011-2022 走看看