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.
  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開始
  • 有一定的規律,因爲當n爲2時,[0,1,3,2]纔是正確的解,但[0,2,3,1]同樣滿足上面的三個條件,但是卻不成立,所以我們需要將這條規律找到,才能解出一道問題的答案。

在這裏插入圖片描述

代碼

import java.util.*;
public class Solution {
    public ArrayList<Integer> grayCode(int n) {
        ArrayList<Integer> list = new ArrayList<>();
        if(n == 0){
            list.add(0);
            return list;
        }
        // 先將n=1的兩種情況添加
        list.add(0);
        list.add(1);
        for(int i = 2; i <= n; i++){
            // 我們通過枚舉法可以知道:list(n) = list(n-1) + list(n-1)的高位爲1的情況
            // 1. 先取到當前集合中的元素個數
            int size = list.size();
            // 2. 倒着遍歷集合,給每個元素的第i-1位改爲1(1 << i-1)
            for(int j = size-1; j >= 0; j--){
                list.add(list.get(j) + (1<<(i-1)));
            }
        }
        return list;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章