Gray Code问题及分析
来源:互联网 发布:万网购买域名能退款吗 编辑:程序博客网 时间:2024/05/17 01:39
问题描述:
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.
示例:
given n = 2, return [0,1,3,2]
. Its gray code sequence is:
00 - 001 - 111 - 310 - 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.
问题分析:
通过分析规律可得如下两种解决方法:
①G(i) = i ^ (i / 2);
②先把原数组分成两份,左边的先保留,右边的数组再分成两份a和b,a和b互换位置;以此回溯,直到 n = 1结束。
过程详见代码(②):
class Solution {public: vector<int> grayCode(int n) {vector<int> res; n = (int)pow(2, n);for (int i = 0; i < n; i++)res.push_back(i);sortGrayCode(res, n, 0);return res;}void sortGrayCode(vector<int>& res,int n,int start){if (n == 1) return;sortGrayCode(res, n / 2, start);for (int i = start + n / 2; i < start + n / 2 + n / 4; i++)swap(res[i], res[i + n / 4]);sortGrayCode(res, n / 2, start + n / 2);}};
阅读全文
0 0
- Gray Code问题及分析
- Gray Code 简介及生成
- gray code 格雷码求解问题
- 【LeetCode】89. Gray Code解法及注释
- [LeetCode 89]Gray Code (格雷码问题)
- 【Leetcode】:89. Gray Code 问题 in JAVA
- Gray Code
- Gray Code
- gray code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- Gray Code
- 常见工具总结
- Jquery之选择器与方法综合练习
- 图的最短路径:Dijkstra、Bellman-Ford、SPFA、Floyd、A*算法
- Hadoop-No.14之文件传输的特点
- Android Manifest 权限描述大全
- Gray Code问题及分析
- MathJax使用LaTeX语法编写数学公式教程
- POJ 1159 Palindrome【LCS+滚动数组】【水题】
- Dijkstra、Bellman_Ford、SPFA、Floyd算法复杂度比较
- extern的用法
- Linux学习笔记——20170805
- R语言爬虫之rvest包初试(一)
- 蒜头君吃桃子
- hdu-6060-RXD and dividing