89. Gray Code

 

public class Solution {
    public List<Integer> grayCode(int n) {
        //格雷码
        /*
        2位元格雷码    
          00    01    11    10 

        3位元格雷码  
          000    001    011    010  
          110    111    101    100  
          
        4位元格雷码  
          0000   0001   0011   0010   0110   0111   0101   0100   
          1100   1101   1111   1110   1010   1011   1001   1000  */
        
        //可以看到,每次多一位的格雷码就是在原有的基础上在头位置添上一个0
        //之后再将0置换为1,并且逆序排布
        if(n==0)
        {
            List<Integer> res0=new ArrayList<Integer>();
            res0.add(0);
            return res0;
        }
        
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        
        for(int i=0;i<n;i++)
        {
            List<Integer> temp=new ArrayList<Integer>();
            if(i==0)//一位格雷码
            {
                
                temp.add(0);
                //添加 0
                temp.add(1);
                //添加 1
                
            }
            else
            {
                int head=(int)Math.pow(2,i);
                for(int j=0;j<head;j++)
                {
                    temp.add(res.get(i-1).get(j));
                }
                for(int j=head-1;j>=0;j--)
                {
                    temp.add(res.get(i-1).get(j)+head);
                }
            }
            res.add(temp);
            
        }
        
        return res.get(n-1);
        
    }
}

 

posted @ 2016-04-04 15:06  阿怪123  阅读(141)  评论(0编辑  收藏  举报