题目地址:
https://www.lintcode.com/problem/gray-code/description
产生所有的 n n n位格雷码。 n n n位格雷码是指 0 ∼ n − 1 0\sim n-1 0∼n−1这 n n n个数的一种排列,使得相邻的两个数的二进制表示只有一位不同,并且首尾也是只有一位不同。
要产生 n n n位格雷码,可以将产生的 n − 1 n-1 n−1位格雷码反序后加上 1 < < ( n − 1 ) = 2 n − 1 1<<(n-1)=2^{n-1} 1<<(n−1)=2n−1。可以用递归实现,也可以直接用for循环实现。代码如下:
import java.util.ArrayList;
import java.util.List;
public class Solution {
/**
* @param n: a number
* @return: Gray code
*/
public List<Integer> grayCode(int n) {
// write your code here
List<Integer> res = new ArrayList<>();
res.add(0);
for (int i = 0; i < n; i++) {
int size = res.size();
for (int j = size - 1; j >= 0; j--) {
res.add(res.get(j) + (1 << i));
}
}
return res;
}
}
时间复杂度 O ( 2 n ) O(2^n) O(2n)。