背景
題目英文
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.
Example 1:
Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2
For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.
00 - 0
10 - 2
11 - 3
01 - 1
Example 2:
Input: 0
Output: [0]
Explanation: We define the gray code sequence to begin with 0.
A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
Therefore, for n = 0 the gray code sequence is [0].
題目中文
格雷編碼是一個二進制數字系統,在該系統中,兩個連續的數值僅有一個位數的差異。
給定一個代表編碼總位數的非負整數 n,打印其格雷編碼序列。格雷編碼序列必須以 0 開頭。
示例 1:
輸入: 2
輸出: [0,1,3,2]
解釋:
00 - 0
01 - 1
11 - 3
10 - 2
對於給定的 n,其格雷編碼序列並不唯一。
例如,[0,2,3,1] 也是一個有效的格雷編碼序列。
00 - 0
10 - 2
11 - 3
01 - 1
示例 2:
輸入: 0
輸出: [0]
解釋: 我們定義格雷編碼序列必須以 0 開頭。
給定編碼總位數爲 n 的格雷編碼序列,其長度爲 2^n。
當 n = 0 時,長度爲 2^0 = 1。
因此,當 n = 0 時,其格雷編碼序列爲 [0]。
算法實現
由 n 位推導 n+1 位結果時,n+1 位結果包含 n 位結果,同時包含 n 位結果中在高位再增加一個位 1 所形成的令一半結果,但是這一半結果需要與前一半結果鏡像排列。
public class Solution
{
public IList<int> GrayCode(int n)
{
IList<int> lst = new List<int>();
lst.Add(0);
for (int i = 1; i <= n; i++)
{
for (int j = lst.Count - 1; j >= 0; j--)
{
int item = lst[j] + (1 << i - 1);
lst.Add(item);
}
}
return lst;
}
}
實驗結果
- 狀態:通過
- 12 / 12 個通過測試用例
- 執行用時: 296 ms, 在所有 C# 提交中擊敗了 95.83% 的用戶
- 內存消耗: 24.8 MB, 在所有 C# 提交中擊敗了 16.67% 的用戶
相關圖文
1. “數組”類算法
- LeetCode實戰:三數之和
- LeetCode實戰:最接近的三數之和
- LeetCode實戰:求衆數
- LeetCode實戰:缺失的第一個正數
- LeetCode實戰:快樂數
- LeetCode實戰:尋找兩個有序數組的中位數
- LeetCode實戰:盛最多水的容器
- LeetCode實戰:刪除排序數組中的重複項
- LeetCode實戰:搜索旋轉排序數組
- LeetCode實戰:螺旋矩陣
- LeetCode實戰:螺旋矩陣 II
2. “鏈表”類算法
- LeetCode實戰:兩數相加
- LeetCode實戰:刪除鏈表的倒數第N個節點
- LeetCode實戰:合併兩個有序鏈表
- LeetCode實戰:合併K個排序鏈表
- LeetCode實戰:兩兩交換鏈表中的節點
- LeetCode實戰:旋轉鏈表
- LeetCode實戰:環形鏈表
3. “棧”類算法
4. “隊列”類算法
5. “遞歸”類算法
6. “字符串”類算法
7. “樹”類算法
8. “哈希”類算法
9. “搜索”類算法
10. “動態規劃”類算法
11. “回溯”類算法
12. “數值分析”類算法