首页 > 其他 > 详细

89. Gray Code

时间:2016-04-04 16:16:24      阅读:224      评论:0      收藏:0      [点我收藏+]

 

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);
        
    }
}

 

89. Gray Code

原文:http://www.cnblogs.com/aguai1992/p/5352062.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!