😕题目描述

😔分析

对于格雷码需要分析他的特征。

  1. 00,01,11,10
  2. 000,001,011,010,110,111,101,100
  3. 0000,0001,0011,0010,0110,0111,0101,0100,1100,1101,1111,1110,1010,1011,1001,1000

**下一个长度的格雷码=("0"+上个长度格雷码)+("1"+上个长度格雷码的逆序)**。
所以就只因此进行递归操作了。

😏答案

func grayCode(n int) []int {
    var temp []string
    temp = append(temp, "0")
    temp = append(temp, "1")

    for i := 1; i < n; i++ {

        newTemp := temp
        for j := len(temp) - 1; j >= 0; j-- {
            newTemp = append(newTemp, temp[j])
        }

        for j := 0; j < len(temp); j++ {
            newTemp[j] = fmt.Sprintf("%s%s", "0", newTemp[j])
            newTemp[j+len(temp)] = fmt.Sprintf("%s%s", "1", newTemp[j+len(temp)])
        }

        temp = newTemp
    }

    res := make([]int, len(temp))

    for i, _ := range temp {
        temp, _ := strconv.ParseInt(temp[i], 2, 17)
        res[i] = int(temp)
    }
    return res
}