Gray Code

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.

思路:

  递归

我的代码:

public class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> list = new ArrayList<Integer>();
        if(n < 0)   return list;
        if(n == 0)
        {
            list.add(0);
            return list;
        }
        list = grayCode(n-1);
        for(int i = list.size()-1; i >=0; i--)
        {
            int num = list.get(i);
            num += (1 << (n-1));
            list.add(num);
        }
        return list;
    }
}
View Code

学习之处:

  • 本应该能做出来的,因为刚看过《剑指offer》题目类似啊,因为上一次刷leetcode存在了思维定式,觉得这次也做不出来
  • 对于n位的问题,先递归的解决n-1位,再看从n-1位转换成n位有什么规律,最后得到n位的结果

posted on 2015-04-27 10:48  zhouzhou0615  阅读(181)  评论(0编辑  收藏  举报

导航