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 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4908208.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值