Jan 23 - Gray Code; BackTracking;

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jan 23 - Gray Code; BackTracking;相关的知识,希望对你有一定的参考价值。

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;的主要内容,如果未能解决你的问题,请参考以下文章

89. Gray Code

89. Gray Code

Gray Code

Gray Code -- LeetCode

LeetCode89. Gray Code

[LeetCode][JavaScript]Gray Code