class Solution {public List grayCode(int n) {List res = new ArrayList<>();res.add(0);int head = 1;for(int i = 1;i<=n;i++){for(int j = res.size() - 1;j>=0;j--){res.add(head + res.get(j));}head <<= 1;}return res;}
}
C语言版
int* grayCode(int n, int* returnSize)
{int* res = (int*)malloc(sizeof(int) * (1 << n));int len = 1 << n;res[0] = 0;int head = 1;int index = 1;for(int i = 1;i<=n;i++){for(int j = index - 1;j>=0;j--){res[index++] = head + res[j];}head <<= 1;}*returnSize = index;return res;
}
Python版
class Solution:def grayCode(self, n: int) -> List[int]:res = [0]head = 1for i in range(1,n+1):for j in range(len(res) - 1,-1,-1):res.append(head + res[j])head <<= 1return res