LeetCode[11] - Grey Code

李特这特题目有点蛋疼,因为目前只接受一种结果。
我做的恰好和它要的结果不一样,但是我觉得我这种走法走出来也是没错的。
基本想法就是从一个点开始往一个方向走,每次flip一个bit, 碰壁的时候就回头走。

/*

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.

Tags:Backtracking

*/

/*

Leetcode tags shows backtracking. That should be different approach than what I hvae below:

*/

/*

TRY: My code works for this run-through, however does not fit the OJ yet

0   0   0   [start, noting happend, flip index 0]

0   0 <-1   [move to flip left adjacent]

0 <-1   1   [move to flip left adjacent]

1-> 1   1   [move to flip right adjacent]

1   0-> 1   [move to flip right adjacent]

1   0 <-0   [move to flip left adjacent]

1 <-1   0   [move to flip left adjacent]

0   1   0   [done]

Conclusion: hit the wall and flip the other direction.

Every flip, add integer to list 

Convert the char[] to string, then Integer.parse(str, 2) to integer

Simulate the steps:

For example, when n = 3, step = n - 1. It takes 2 steps from right side to reach left side, it hits the wall and turn around.

Now:

1. Initialize char[] and add '000'

2. do for loop on 1 ~ 2^n -2. last step '010' is stepped into, but no further action, so take 2^3 - 1 = 7 steps.

*/

public class Solution {

public List<Integer> grayCode(int n) {

List<Integer> rst = new ArrayList<Integer>();

if (n < 0) {

return rst;

}

char[] bits = new char[n];

for (int i = 0; i < bits.length; i++) {

bits[i] = '0';

}

String str = new String(bits);

if (n == 0) {

str = "0";

}

rst.add(Integer.parseInt(str, 2));

int step = n - 1;

boolean LR = true;//L: true; R: false

int steps = (int)Math.pow(2, n) - 1;

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

bits[step] = bits[step] == '0' ? '1' : '0';

str = new String(bits);

rst.add(Integer.parseInt(str, 2));

if (LR) {

step--;

} else {

step++;

}

if (step == (n - 1) || step == 0) {//Turn around

LR = !LR;

}

}

return rst;

}

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 人们都长着一对隐形触角,只是他们自己不知道,当两只触角充斥脏恶不堪就会变成一摊细长的触须,贴紧地面,诱惑着它上勾。...
    梅晶有只乌鸦阅读 1,365评论 2 2
  • 5.1表叔的女儿丽过来找我玩,照辈分我要叫她姨妈,因为她只比我大几个月,从小我便叫她名字。妈妈经常说我,我也不以为...
    红猪猪阅读 1,384评论 0 1
  • 天气转凉了,你妈和你姨说要陪我去选地方了。因为腿脚越来越不好,怕哪天走不动了,她们选的不合我意,所以我早早地就...
    飞的天阅读 2,206评论 4 2
  • 前不久,刚过了自己20岁的生日。出门在外,没有和家人在一起,也没有找朋友一起出去嗨,只是一个人照常吃食堂,规规矩矩...
    心有林息阅读 2,540评论 0 0