【DP】格雷码
来源:互联网 发布:怎样迫使淘宝店铺停业 编辑:程序博客网 时间:2024/06/07 14:55
题目描述
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.
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.
确实没有找到规律....思路参考的题解。
递推公式:n每增加一位,其格雷码为上一次的格雷码顺次添加0再逆向添加1,如:
00 01 11 10———>000 001 011 010 110 111 101 100....
T T真的强...
ps 吐槽一下判题系统,n=0返回0为的格雷码,0位不应该是空吗...竟然还需要返回个0
import java.util.ArrayList;public class Solution { public ArrayList<Integer> grayCode(int n) { ArrayList<Integer> res = new ArrayList<Integer> (); if(n == 0){ res.add(0); return res; } res.add(0);res.add(1); if(n == 1) return res; int base = 1; while(base != n){ for(int i = res.size() - 1; i >= 0; --i){ int temp = res.get(i); temp = temp | (1<<base); res.add(temp); } base++; } return res; }}
阅读全文
0 0
- 【DP】格雷码
- hdu5375 格雷码性质 dp
- dp
- dp
- dp
- 【DP】
- dp
- dp
- DP
- DP
- DP
- DP
- DP
- dp
- DP
- dp
- DP
- DP
- shell的简单批量curl接口脚本
- MySQL学习续篇--01
- java中的异常处理
- 测试代码
- mysql中大事物提交延迟问题及解决方法
- 【DP】格雷码
- 项目之余安装Wechat----传文件!
- Linux端口状态查看,端口的打开与关闭
- [kuangbin带你飞]专题一 简单搜索 N
- JAVA互联网架构学习之Spring其二数据库连接池及注解配置bean等
- scala自定义控制结构
- Macaca-python-iOS/Android环境搭建
- Go环境搭建:ubuntu+liteide
- spring boot hello Double 7 Day