Saturday, January 10, 2015

LeetCode 89: Gray Code

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.
public class Solution {
    public List<Integer> grayCode(int n) {
        // DP problem
        // n = 0, result = [0]
        // n = 1, result = [0, 1]
        // n = 2, result = [00, 01, 11, 10]
        // n = 3, result = [000,001,011,010,110,111,101,100]
        // For (n+1) bit gray code, result = '0' + (n bit gray code) && '1' + reverse(n bit gray code)
        // Acturally, (n+1) bit result is n bit result with '1' + reverse(n bit gray code).
        List<Integer> result = new LinkedList<Integer>();
        
        if (n < 0)
            return result;
        
        result.add(0);
        
        if (n == 0)
            return result;
            
        result.add(1);
        
        for (int i = 1; i < n; i++)
        {  
            List<Integer> newResult = new LinkedList<Integer>();
            
            // Copy original 'result' to 'newResult' as the first part
            for (int j = 0; j < result.size(); j++)
                newResult.add(result.get(j));
            
            // '1' + Reverse 'result' as the second part     
            for (int k = result.size() - 1; k >= 0; k--)
                newResult.add((int)Math.pow(2, i) + result.get(k));
                
            result = newResult;
        } 
        
        return result; 
    }
}

No comments:

Post a Comment