1. 程式人生 > >LeetCode OJ 89. Gray Code

LeetCode OJ 89. Gray Code

etc back ali i++ unique code with int length

題目

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.

解答

這就是離散數學裏面一個格雷碼的快速推導算法。。。

比如2位格雷碼是00 01 11 10,這個數列奇數項左移後先加0再加1,偶數項左移後先加1再加0,按順序組成的數列就是3位格雷碼000 001 011 010 110 111 101 100。原理很簡單,因為本來就是兩兩相鄰之間差一位,現在按照這樣操作,左移擴展一位,而新加的這一位又是01100110,這樣原來每個數都擴展為相鄰差一位,而原來相鄰差一位的兩個數之間加的是同樣的一位數。

下面是AC的代碼:

class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> ans;
        vector<int
> temp; ans.push_back(0); for(int i = 0; i < n; i++){ int length = ans.size(); temp.clear(); for(int i = 0; i < length; i++){ if(i % 2 == 0){ temp.push_back(ans[i] * 2 + 0); temp.push_back(ans[i] * 2 + 1); } else{ temp.push_back(ans[i] * 2 + 1); temp.push_back(ans[i] * 2 + 0); } } ans = temp; } return ans; } };

119

LeetCode OJ 89. Gray Code