zoukankan      html  css  js  c++  java
  • 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位的结果
  • 相关阅读:
    LINUX 内核守护进程
    LINUX 内核 API
    LINUX IO 图解
    doxygen
    xtrace
    Dapper-translation 分布式监控系统
    矩表
    最流行的5个前端框架对比
    2017年前端框架、类库、工具大比拼
    Top 10 JavaScript编辑器,你在用哪个?
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4459468.html
Copyright © 2011-2022 走看看