zoukankan      html  css  js  c++  java
  • LeetCode: Gray Code

    LeetCode: Gray Code

    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
    

    Note:
    For a given n, a gray code sequence is not uniquely defined.

    For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

    For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

    地址:https://oj.leetcode.com/problems/gray-code/

    算法:假设我们已经完成了前面i位的Gray 码,那么前面i+1位Gray应该按如下构造,首先是第i+1位为零部分,其后的i位跟前面i位Gray码一致,然后紧接着是第i+1位为1的部分,其后的i位按前面i位Gray码的逆序排。假如,n=2Gray码为00 01 11 10,那么n=3的Gray码为000 001 011 010 110 111 101 100。代码:

     1 class Solution {
     2 public:
     3     vector<int> grayCode(int n) {
     4         vector<int> result;
     5         if(n < 0)   return result;
     6         result.push_back(0);
     7         if(n == 0)  return result;
     8         result.push_back(1);
     9         for(int i = 1; i < n; ++i){
    10             int len = result.size();
    11             int temp = 1 << i;
    12             for(int j = len-1; j >= 0; --j){
    13                 result.push_back(result[j] + temp);
    14             }
    15         }
    16         return result;
    17     }
    18 };
  • 相关阅读:
    111
    RH124-3 目录结构_转
    oracle 查看表空间以及日志文件等系统文件
    bash_profile
    linux 7 关闭防火墙 开启sshd服务
    mount 挂载光盘
    oracle 夸服务器、数据库查询
    Oracle中merge into的使用
    restore和recover的区别
    TCP: time wait bucket table overflow解决方法
  • 原文地址:https://www.cnblogs.com/boostable/p/leetcode_gray_code.html
Copyright © 2011-2022 走看看