LeetCode OJ - Gray Code

1929 단어
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.
아이디어 1:
인접 위치가 변하고 경계에 이르면 다른 경계로 바뀌어 변화를 시작한다.만들어진 것도 그레코드였지만, 결과는 제목의 요구에 부합되지 않았다.
class Solution {
    vector<int> ret;
public:
    vector<int> grayCode(int n) {
        if(n < 0 || n > 32) return ret;
        
        int start = 0;
    	int bit = 0, flag = 1;
        int count = 1 << n;
        for(int i = 0 ; i < count; i++) {
            if(i == 0) {
                ret.push_back(start);
                continue;
            }
    
            start ^= 1 << bit;
            ret.push_back(start);
            
            if(n == 1) break;
    	    int region = i % (2 * n - 2);
            if(region >= 1 && region <= n - 1) {
    	        bit++;	 
    	    } else {
    	        bit--;
            }     
        }
        return ret;
    }
};

사고방식2: 1->2->4 더하기 0 총 2^N 개
class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> ret(1, 0);
        while(n--) {
            int highbit = ret.size();
            for(int i = highbit - 1; i >= 0; i--) {
                ret.push_back(highbit | ret[i]);
            }
        }
        return ret;
    }
};

좋은 웹페이지 즐겨찾기