LeetCode Gray Code
原题链接在这里: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:
1 public class Solution { 2 public List<Integer> grayCode(int n) { 3 List<Integer> res = new ArrayList<Integer>(); 4 if(n<0){ 5 return res; 6 } 7 //when n = 0, return [0] 8 res.add(0); 9 for(int i = 0; i<n; i++){ 10 int len = res.size(); 11 //addNum 是要加的首位1 12 int addNum = 1<<i; 13 for(int j = len-1; j>=0; j--){ 14 res.add(addNum+res.get(j)); 15 } 16 } 17 return res; 18 } 19 }