第n位的格雷码由两部分构成,一部分是n-1位格雷码,再加上 1<<(n-1)和n-1位格雷码的逆序的和
public List<Integer> grayCode(int n) {
if (n==0) {
List<Integer> result = new ArrayList<Integer>();
result.add(0);
return result;
}
List<Integer> prevList = grayCode(n-1);
int highestBit = 1 << (n-1);
List<Integer> result = new ArrayList<Integer>(prevList);
for (int i=prevList.size() - 1; i>=0; i--) {
result.add(highestBit + prevList.get(i));
}
return result;
}
No comments:
Post a Comment