java 格雷码_格雷码

48

90d2162b8f5594c1de666a3931ff1416.png

//随着n变大,前面的数不用动,后面的数倒着拿出来再在首部加1即可

class Solution {

public:

vector grayCode(int n) {

vector result;

result.push_back(0);

for (int i = 0; i < n; i++) {

const int hight_bit = 1 << i;

for (int j = result.size() - 1; j >= 0; j--) //第二遍反着遍历,形成对称

result.push_back(hight_bit | result[j]);

}

return result;

}

};

编辑于 2016-09-01 20:00:20

回复(7)

17

//LeetCode上的题目,如下

import java.util.*;

public class Solution {

public ArrayList grayCode(int n) {

ArrayList arr = new ArrayList();

int num = 1 << n;

for(int i = 0; i < num; ++i){

arr.add(i>>1^i);

}

return arr;

}

}

发表于 2016-03-26 12:08:09

回复(19)

8

class Solution {

public:

vector grayCode(int n) {

vector result(pow(2,n));

for (int i=1;i<=n;++i)

{

int size = 1<

int flag = 1<

int index = 0;

for (int j=size-1;2*j>=size;--j)

{

result[j] = result[index++]|flag; //左部插入1

}

}

return result;

}

};

当n=1时,为[0,1]

当n=2时,为[00,01,11,10]

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

由此可以看出新的序列其实是在前面序列基础上插入新的值

其中前半部分的数值不变,后半部分的数值为上个序列中每个元素第n个位变1,逆向插入

发表于 2016-08-13 21:44:28

回复(1)

3

这道题难在找 dp 方程

先看n=2 (00, 01, 11, 10)

n = 3      ((000, 001, 011, 010), (100,101,111,110))

以此类推, n=k时,就是在n=k-1的前面加上0或者1,然后使得数据扩大2倍

DP转移方程如下:

dp[k] = dp[k-1] | 1<

class Solution {

public:

vector grayCode(int n) {

vector res(1,0);

for(int i=0; i

for(int j=res.size()-1; j>=0; j--){

res.push_back(res[j]|1<

}

}

return res;

}

};

发表于 2018-08-26 09:45:58

回复(0)

2

class S

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值