LeetCode-89-格雷编码-C语言

/*
 *  算法思想:
 *  使用递归的思想,求N位grey码,将其转化为N-1位的grey码。
 *  一位:0  两位:  01  三位:001
 *       1          00       000
 *                  10       010
 *                  11       011
 *                           111
 *                           110
 *                           100
 *                           101
 */ 
                      
#define LEN 0xffff

#define NUM_LEN    32

/* 递归函数,用于获取grey码 */
void get_ans(char **ret, int *ret_index, int index) {
    
    //printf("index = %d\n", index);
    
    /* 递归截至条件,当index==1表示只有1位时,前两个结果如下
     * 1位:0 ,设置完前两个数后返回。  
     *     1       
     */
    if(index == 1){
        ret[(*ret_index)] = (char *)malloc(sizeof(char) * NUM_LEN);
        memset(ret[(*ret_index)], 0, NUM_LEN);
        ret[(*ret_index)++][index-1] = '0';

        ret[(*ret_index)] = (char *)malloc(sizeof(char) * NUM_LEN);
        memset(ret[(*ret_index)], 0, NUM_LEN);
        
        ret[(*ret_index)++][index-1] = '1';
        return ;
    }
    
    /* 对于index位的grey码,需要先求出index-1位的grey码,因此递归调用该函数,参数位数为index-1 */
    get_ans(ret, ret_index, index-1);
    
    /* 以为代码为基于index-1位grey码,得出index位grey码 */
    
    /* set first half exist */
    int i;
    for(i=((*ret_index)-1); i>=0; i--){
        /* 已经存在的最后index-1位全部设置为0 */
        ret[i][index-1] = '0';
        //printf("ret[%d] = %s \n", i, ret[i]);
    }
    
    int cnt = (*ret_index-1); 
    
    /* 复制前一半数目的grey码,并且最后一位设置为1 */
    for(i=cnt; i>=0; i--){
        ret[(*ret_index)] = (char *)malloc(sizeof(char) * NUM_LEN);
        memset(ret[(*ret_index)], 0, NUM_LEN);
        memcpy(ret[(*ret_index)], ret[i], index-1);
        
        ret[(*ret_index)][index-1] = '1';/* 后来新复制的后半部分grey码的 index-1位全部设置为1 */
        
        (*ret_index)++;
        //printf("ret[%d] = %s \n", i, ret[i]);
    }
}

/* 将字符串转化为整数 */
int get_num(char *s){
    int ret=0;
    while(*s){
        ret *= 2;
        ret += *s - '0';
        s++;
    }
    return ret;
}

int* grayCode(int n, int* returnSize){
    char **ret = (char **)malloc(sizeof(char) * LEN);
    int ret_index = 0;
    
    /* 处理n==0 时候的特殊情况 */
    if(n == 0){
        int *ans = (int *)malloc(sizeof(int));
        ans[0] = 0;
        *returnSize = 1;
        return ans;
    }
    
    /* 调用递归函数获取grey码以及总个数,使用字符串存储 */
    get_ans(ret, &ret_index, n);
    
    int *ans = (int *)malloc(sizeof(int) * ret_index);
    int i;
    for(i=0; i<ret_index; i++) {
        ans[i] = get_num(ret[i]);
        /* free buffers */
        free(ret[i]);
    }
    
    free(ret);
    
    
    *returnSize = ret_index;
    
    return ans;
}


猜你喜欢

转载自blog.csdn.net/weixin_36094222/article/details/90180585
今日推荐