您的位置:首页 > 其它

LeetCode Gray Code

2015-10-25 08:43 381 查看
原题链接在这里:https://leetcode.com/problems/gray-code/

题目:

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

题解:

根据graycode的特性:在n增大1时,在原有list的末尾按照原有list的倒序每个数字首位digit加上一个1 加回到list中.

n = 0时,[0]

n = 1时,[0,1]

n = 2时,[00,01,11,10] 原有[0,1], 按照倒序[1,0], 首位加1变成[11,10]加回到原有的[0,1]后面, 就变成[0, 1, 11, 10]了.

n = 3时,[000,001,011,010,110,111,101,100]

Time Complexity: O(2^n). Space: O(1).不考虑res.

AC Java:

public class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<Integer>();
if(n<0){
return res;
}
//when n = 0, return [0]
res.add(0);
for(int i = 0; i<n; i++){
int len = res.size();
//addNum 是要加的首位1
int addNum = 1<<i;
for(int j = len-1; j>=0; j--){
res.add(addNum+res.get(j));
}
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: