Leetcode 89(Java)
来源:互联网 发布:软件开发很难吗 编辑:程序博客网 时间:2024/06/05 18:24
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=1时,result里有0,1。当n=2时,result里为00,01,11,10,当 n不断累加,我们不难发现,每一个n对应的结果,可以讲上一个n-1对应结果里的内容复制一份,然后在前一份最高位+0,后一份最高位+1。既然每一个n的结果都是与n-1相关,不难想到用 回溯法。AC码如下:
public class Solution { public List<Integer> grayCode(int n) { if(n==0){ List<Integer> result = new ArrayList<>(); result.add(0); return result; } List<Integer> result = grayCode(n-1); int originSize = result.size(); int addN = 1 << (n-1); for(int i = originSize-1;i>=0;i--) result.add(addN+result.get(i)); return result; }}
- Leetcode 89(Java)
- Leetcode(java)
- leetcode java
- LeetCode 89(Gray Code)java
- [LeetCode]Next Permutation java leetcode
- LeetCode: Two Sum (Java)
- [Leetcode] Two Sum (Java)
- [Leetcode] ZigZag Conversion (Java)
- [Leetcode] Reverse Integer (Java)
- [Leetcode] Palindrome Number (Java)
- [Leetcode] Valid Parentheses (Java)
- [Leetcode] Generate Parentheses (Java)
- [Leetcode] Remove Element (Java)
- [Leetcode] Implement strStr() (Java)
- [Leetcode] Next Permutation (Java)
- [Leetcode] Valid Sudoku (Java)
- [Leetcode] Sudoku Solver (Java)
- [Leetcode] Combination Sum (Java)
- Android13
- SQL Server2008新实例远程数据库链接问题(sp_addlinkedserver)
- hadoop的安装与配置方法详解
- 泛型
- squid与bond0
- Leetcode 89(Java)
- [YTU]_2535 (Problem I: C++复数运算符重载(+与<<))
- Android14
- Hive分析窗口函数(一) SUM,AVG,MIN,MAX
- PayPal Android SDK的接入和开发、与服务器对接IPN
- Android15
- 程序员的进化史
- PCL获取Kinect v2点云
- Android16