您好,欢迎来到保捱科技网。
搜索
您的当前位置:首页【Leetcode】之Gray Code

【Leetcode】之Gray Code

来源:保捱科技网

一.问题描述

The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

00 - 0
01 - 1
11 - 3
10 - 2

Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

二.我的解题思路

拿到题目观察一番,就不难想到可以用分治递归的算法思想去解决。具体实现起来也比较容易,测试通过的程序如下:

class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> res(pow(2.0,n),0);
        if(n<=0) return res;
        gen_code(res,n);
        return res;
    }
    
    void gen_code(vector<int>& res,int n){
        if(n==1){
            res[0]=0;
            res[1]=1;
            return;
        }
        int curr_num=pow(2.0,n-1);
        gen_code(res,n-1);
        for(int i=curr_num;i<2*curr_num;i++){
            res[i]=pow(2.0,n-1)+res[2*curr_num-i-1];
        }
    }
};




因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baoaiwan.cn 版权所有 赣ICP备2024042794号-3

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务