【leetcode】【89】Gray Code

原创 2015年11月17日 16:43:15

一、问题描述

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.

二、问题分析

通过观察我们可以可以发现,

当n=1时,gray code 为 0,1;

当n=2时,gray code 为 00,01,11,10

当n=3时,gray code 为 000,001,011,010,110,111,101,100

我们可以发现,比如n=3时 黑色的部分即为n=2时的全部,而红色部分是首位为1,余下的两位为n=2时的逆序组合(例如,n=2时最后一个为10,而n=3时的红色部分为110,n=2时的倒数第二个为11,n=3时的红色部分的第二个为111,以此类推)

我们可以采用递归和迭代两种方式

题目的tags表明该题可以采用backtracking,但写起来并不太容易

三、Java AC 代码

迭代

public List<Integer> grayCode(int n) {
        ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(0);
		for (int i = 0; i < n; i++) {
			int highest = 1 << i;
			for(int j = list.size()-1;j>=0;j--){
				list.add(list.get(j)+highest);
			}
		}
		return list;
    }


递归

public List<Integer> grayCode(int n) {
        if (n==0) {
			List<Integer> list = new ArrayList<Integer>();
			list.add(0);
			return list;
		}
		List<Integer> list = grayCode(n-1);
		int highest = 1 << (n-1);
		for (int i = list.size()-1; i >= 0; i--) {
			list.add(list.get(i)+highest);
		}
		return list;
    }


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode 89. Gray Code(格雷码)

原题网址:https://leetcode.com/problems/gray-code/ The gray code is a binary numeral system where two s...

LeetCode 89 Gray Code

The gray code is a binary numeral system where two successive values differ in only one bit. Given ...

LeetCode #89 - Gray Code - Medium

ProblemThe gray code is a binary numeral system where two successive values differ in only one bit.G...

[leetcode] 【数组】 89. Gray Code

The gray code is a binary numeral system where two successive values differ in only one bit. Give...

89. Gray Code [leetcode]

89. Gray Code The gray code is a binary numeral system where two successive values differ in only...

LeetCode89/60 Gray Code/Permutation Sequence--迭代

一:Leetcode 89 Gray Code 题目:The gray code is a binary numeral system where two successive values...

LeetCode_89_Gray Code 格雷码

题目描述 The gray code is a binary numeral system where two successive values differ in only one bit. ...

LeetCode 89: Gray Code解题报告

LeetCode89: Gray Code题解报告 提交网址: https://leetcode.com/problems/gray-code/  89. Gray Code Tot...

[leetcode] 89. Gray Code 解题报告

题目链接:https://leetcode.com/problems/gray-code/ The gray code is a binary numeral system where two s...

leetcode 89 Gray Code

leetcode 89 Gray Code Python C++
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)