码迷,mamicode.com
首页 > 其他好文 > 详细

Jan 23 - Gray Code; BackTracking;

时间:2016-01-24 11:29:48      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

We can find the regular pattern in gray code, which is:

the first of the combinations of n-digit gray code is exactly the combinations of (n-1)-digit gray code, the second half is consist of 1<<(n-1) + each elements from the end to the start in (n-1)-digit gray code. 

 

code:

public class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> list = new ArrayList<>();
        if(n == 0){
            list.add(0);
            return list;
        }
        if(n == 1){
            list.add(0);
            list.add(1);
            return list;
        }
        int i = 1 << (n-1);
        list = grayCode(n-1);
        for(int j = list.size() - 1; j >=0; j--) list.add(i+list.get(j));
        return list;
    }
}

 

Jan 23 - Gray Code; BackTracking;

标签:

原文地址:http://www.cnblogs.com/5683yue/p/5154792.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!