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位的结果
  • 相关阅读:
    JVM内存问题分析
    CAS
    普通内部类,匿名内部类和静态内部类
    文章简介
    conda更换下载源
    MySQL常见约束
    MySQL常见的数据类型
    DDL(数据定义语言)
    DML语言(数据操纵语言)
    进阶9:联合查询
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4459468.html
Copyright © 2011-2022 走看看