算法题LC60:minimum-depth-of-binary-tree

动态规划:
题目描述
格雷码是一种二进制编码系统,如果任意两个相邻的代码只有一位二进制数不同,则称这种编码为格雷码(Gray Code)。
给定一个非负整数n,表示代码的位数,打印格雷码的序列。格雷码序列必须以0开头。
例如:给定n=2,返回[0,1,3,2]. 格雷码的序列为:
00 - 0↵01 - 1↵11 - 3↵10 - 2
注意:
对于一个给定的n,格雷码的序列不一定是唯一的,
例如:根据题目描述,[0,2,3,1]也是一个有效的格雷码序列

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.

输入描述

输出描述

示例1:
输入

输出
        
代码:

import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> grayCode(int n) {
        ArrayList<Integer> result = new ArrayList<>();
        if (n < 0)
            return result;
        if (n == 0) {
            result.add(0);
            return result;
        }
        result.add(0);
        result.add(1);
        for (int i = 2; i <= n; i++) {
            int size = result.size();
            for (int j = size - 1; j >= 0; j--) {
                result.add(result.get(j) + (1<<(i-1)));
            }
        }
        return result;
    }
}
发布了80 篇原创文章 · 获赞 1 · 访问量 1401

猜你喜欢

转载自blog.csdn.net/alidingding/article/details/104673438