LeetCode89——Gray Code
来源:互联网 发布:辐射4室内光源优化 编辑:程序博客网 时间:2024/06/06 01:41
LeetCode89——Gray Code
通过二进制和递归两种方式求解n位生成格雷码(十进制表示)..
原题
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
二进制生成格雷码
首先是比较简单的“平民”算法,之前学过数字电路应该有相关的内容:
第
即对应二进制相邻位的异或,其中计算时在二进制的最高位之前补0。
二进制与格雷码表如图所示:
二进制到格雷码转换示意图:
由此本题的基本步骤思路为:
1. n位二进制数可表示
2. 由二进制数转换为格雷码
3. 格雷码生成十进制数(按照二进制数转十进制数的方法进行)
代码:
比较繁琐,但相对比较好理解。
class Solution {private: int binary2grey(vector<int>binary) { vector<int>greyCode; for (int i = 0; i < binary.size() - 1; i++) { greyCode.push_back(binary[i] ^ binary[i + 1]); }//二进制到格雷码 int sum = 0; for (int i = greyCode.size() - 1; i >= 0; i--) { sum += greyCode[i] << (greyCode.size() - 1 - i); }//格雷码到十进制 return sum; } vector<int> num2Binary(int nums)//十进制转二进制 { vector<int>result; while (nums) { result.insert(result.begin(), nums % 2); nums /= 2; } result.insert(result.begin(), 0); return result; }public: vector<int> grayCode(int n) { int bits = pow(2, n); vector<int>result; //num2Binary(6); for (int i = 0; i < bits; i++) { vector<int>binary = num2Binary(i);//十进制转二进制 int grey = binary2grey(binary);//二进制->格雷码->十进制 result.push_back(grey);//写入结果 } return result; }};
格雷码的递归求解
根据格雷码的特性,可以知道欲求n位生成格雷码,必须用到n-1位生成格雷码
其规律是:
n位生成格雷码的前
n位生成格雷码的前
例如:
2位生成格雷码为:
00
01
11
10
按照上述规律:
3为生成格雷码的前4项为:
000
001
011
010
后4项为:
110
111
101
100
8项依次按顺序即为所求结果(注意是对称的)。
因此使用递归求解:
代码:
class Solution { public: vector<int> grayCode(int n) { vector<int>gray; if (n == 0) { gray.push_back(0); //gray.push_back(1); return gray; } vector<int> preGray = grayCode(n - 1); vector<int>resGray(preGray);//前 2^(n-1)个数 for (int i = preGray.size() - 1; i >= 0; i--) { int temp = preGray[i] + pow(2, n - 1); resGray.push_back(temp); }//后2^(n-1)个数 return resGray; }};
- LeetCode89——Gray Code
- LeetCode89:Gray Code
- LeetCode89. Gray Code
- LeetCode89. Gray Code
- leetcode89-Gray Code(格雷码)
- leetcode89: Gray Code
- leetcode89~Gray Code
- Leetcode89. Gray Code
- leetcode89. Gray Code
- LeetCode89 Gray Code
- LeetCode89/60 Gray Code/Permutation Sequence--迭代
- LeetCode——Gray Code
- leetcode——Gray Code
- LeetCode——Gray Code
- Algorithms—89.Gray Code
- leetcode 089 —— Gray Code
- 递归——生成格雷码(gray code)
- 算法系列——Gray Code
- 解决python递归栈溢出
- Linux运维工程师入门须掌握的10个技术点
- AsyncTask可能有的坑-Android
- 《数据结构》带头结点单链表的合并
- HTML,CSS,font-family:中文字体的英文名称 (宋体 微软雅黑)
- LeetCode89——Gray Code
- 算法代码实现之冒泡排序,Java实现
- 14.UIPickerView
- 【VIP】205. Isomorphic Strings【E】【61】【太经典了】
- 原码,补码和反码总结
- Android如何获得当前应用显示的Activity
- python字典
- hdu 2896 病毒侵袭
- Win7 64位 Visio 32位 "驱动程序和应用程序之间的体系结构不匹配 问题解决 本人亲测"