We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
原题链接: https://leetcode.cn/problems/gray-code/
解题思路:
n - 1
n
n = 3
[00, 01, 11, 10]
0
[000, 001, 011, 010]
10
110
11
111
01
101
00
100
[000, 001, 011, 010, 110, 111, 101, 100]
1
10 | 100 = 110
/** * @param {number} n * @return {number[]} */ var grayCode = function (n) { let result = [0] // 存储结果,第一个整数位0 // 一共计算n位格雷码序列,需要循环n位 for (let i = 0; i < n; i++) { // 每次计算时,已有的序列不变 // 只需要计算已有序列的逆序列,每个再加前缀1 // 需要缓存已有序列的长度,用于计算下一段序列 const len = result.length // 由于是逆序计算,因此要从len - 1开始加前缀 for (let j = len - 1; j >= 0; j--) { // 加前缀1后,把新值存入结果 result.push(result[j] | (1 << i)) } } return result }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
原题链接:
https://leetcode.cn/problems/gray-code/
解题思路:
n - 1
的序列,那么n
位的序列就等于已有的n - 1
序列,再加上逆序书写的n - 1
序列,在逆序数列的前面加上1即可。n = 3
时,n - 1
即2位的序列为[00, 01, 11, 10]
[00, 01, 11, 10]
前面加前缀0
,得到[000, 001, 011, 010]
10
加前缀1,得到110
11
加前缀1,得到111
01
加前缀1,得到101
00
加前缀1,得到100
[000, 001, 011, 010, 110, 111, 101, 100]
10
为例:1
向左移动2位,得到100
10
与100
进行“或”位运算,即10 | 100 = 110
The text was updated successfully, but these errors were encountered: