Leetcode Gray Code

来源:互联网 发布:长春知满天教育怎么样 编辑:程序博客网 时间:2024/04/29 10:23

题意:

        给出一组n位的Gray Code。

思路:

        之前想用模拟的方法求解,发现时间复杂度有点高。参考了wiki上的生成方法:https://en.wikipedia.org/wiki/Gray_code

        n*(n/2)


代码如下:

/** * Return an array of size *returnSize. * Note: The returned array must be malloced, assume caller calls free(). */int* grayCode(int n, int* returnSize) {    int k=pow(2,n);    int i,j;    int *p=(int*)malloc(sizeof(int)*k);    for(i=0;i<k;++i){        *(p+i)=i^(i/2);    }    *returnSize=k;    return p;}



0 0
原创粉丝点击