[Leetcode] 89. Gray Code 解题报告
来源:互联网 发布:qq数据储存在哪里 编辑:程序博客网 时间:2024/06/16 16:21
题目:
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 - 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.
思路:
总结该题目的规律:假设对于(n-1)而言,我们已经计算出来了gray code的序列grayCode(n-1),那么对于n而言,一个可行的办法是什么呢?由于grayCode(n)中的每个元素都有n个二进制位,所以我们可以将grayCode(n)分为两部分,第一部分是首位为0的元素,第二部分是首位位1的元素。可以发现,其中第一部分恰好就是grayCode(n-1)中的元素。那么如果我们依次将第一部分的元素首位都变成1,然后逆序加入序列,不就构成了grayCode(n)的结果吗?下面的代码正是这一思路的结果,我们用递归实现了这一算法。
代码:
class Solution {public: vector<int> grayCode(int n) { vector<int> result = {0}; if (n == 0) { return result; } else if (n == 1) { result.push_back(1); return result; } result = grayCode(n-1); int half_size = result.size(); int added_value = 1 << (n - 1); for(int i = half_size - 1; i >= 0; --i) { result.push_back(added_value + result[i]); } return result; }};
- [leetcode] 89. Gray Code 解题报告
- Leetcode 89. Gray Code 格雷码 解题报告
- [Leetcode] 89. Gray Code 解题报告
- [LeetCode] Gray Code 解题报告
- LeetCode 89: Gray Code解题报告
- Gray Code解题报告
- hdu 5375 - Gray code(dp) 解题报告
- leetCode 89.Gray Code (格雷码) 解题思路和方法
- [LeetCode]89.Gray Code
- LeetCode 89. Gray Code
- [Leetcode] 89. Gray Code
- LeetCode --- 89. Gray Code
- [leetcode] 89.Gray Code
- 89. Gray Code LeetCode
- [LeetCode]89. Gray Code
- Leetcode 89. Gray Code
- [leetcode] 89. Gray Code
- LeetCode *** 89. Gray Code
- 75道程序员面试逻辑思维题
- 完美解决FragmentPagerAdapter刷新问题
- DBUS通信C/C++/Python/Nodejs编译调试整理
- 百度云盘下载无限制 云视云百度网盘工具1.3正式版
- jQuery的常用方法
- [Leetcode] 89. Gray Code 解题报告
- hibernate配置文件hibernate.cfg.xml和.hbm.xml的详细解释
- 神经网络之感知器与词向量
- Homework 1-2
- AS、LIKE、IN
- HTTP 2 的新特性你 get 了吗?
- 最常见的Linux用户程序异常----Segment Fault
- NYOJ 168
- 数据库<6>