[leetcode刷题系列]Gray Code
来源:互联网 发布:java工作流视频教程 编辑:程序博客网 时间:2024/06/12 21:33
前两天刚看了组合数学求关于求combination的那节, 里面讲到了如何求Gray Code。 正好留意到题目标题有带Gray字眼的,就打开看了下。
关于详细算法过程的说明以及证明可以在组合数学中找到, 这里就不说了。
class Solution { int get_next(int now, int n){ int num_bit = 0; int tmp = now; while(tmp > 0){ num_bit ^= 1; tmp &= (tmp - 1); } if(num_bit & 1){ for(int i = 0; i < n - 1; ++ i) if(now & (1 << i)) return now ^ (1 << i + 1); return 0; }else{ return now ^ 1; } }public: vector<int> grayCode(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> vc; if(n == 0){ vc.push_back(0); return vc; } int now = 0; do{ vc.push_back(now); }while((now = get_next(now, n)) != 0); return vc; }};
===========我是分割线=================
下面的解法是在北美求职群看到的, 和上面得到的序列貌似是一样的。
关于这两种方法为什么是等价的问题上, 由于智力问题, 我无法得到一个很直观的解释。
不过倒是可以很容易证明为啥下面的方法的是正确的。这里就不说了,看到的同学可以自己想一下。
class Solution {public: vector<int> grayCode(int n) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<int> ret(1 << n); for(int i = 0; i < (1 << n); ++ i) ret[i] = i ^ (i >> 1); return ret; }};
- [leetcode刷题系列]Gray Code
- LeetCode刷题笔录Gray Code
- leetcode 刷题之路 89 Gray Code
- 开始刷leetcode day47:Gray Code
- leetcode 第89题 Gray Code
- *LeetCode 89. Gray Code 规律题
- LeetCode: Gray Code
- [LeetCode] 格雷码(Gray Code)
- LeetCode Gray Code
- [Leetcode] Gray Code
- [LeetCode] Gray Code
- leetcode 112: Gray Code
- LeetCode Gray Code
- [leetCode] Gray Code
- [LeetCode]Gray Code
- Leetcode: Gray Code
- [leetcode]Gray Code
- LeetCode-Gray Code
- Windows Server 2008 R2 官方原版下载大全
- 黑马程序员 java高新技术之代理和AOP原理
- 一道经典的sql面试题不同的写法
- iOS: UIScrollView的方法setZoomScale:animated:
- <转载>MyEclipse下载 各版本和32和64位w分类
- [leetcode刷题系列]Gray Code
- 排序算法Java实现
- iOS: UIScrollView的方法touchesShouldBegin:withEvent:inContentView:
- HDU1251 统计难题 解题报告--字典树
- 继承 实现 依赖 关联 聚合 组合之间的关系和联系
- python84
- 查找算法Java实现
- iOS: UIScrollView的方法touchesShouldCancelInContentView:
- LXC 轻量级虚拟化