腾讯笔试:>格雷码

/* 腾讯笔试:>格雷码 */

vector<int> Gray_Create(int n)
{
    vector<int> res;
    for (int i = 0; i < (1 << n); ++i)
    {
        res.push_back(i ^ (i >> 1));
    }
    return res;
}

//void test()
//{
// vector<int>res = Gray_Create(3);
// for (int i = 0; i < res.size(); ++i)
// cout << res[i];
//}

vector<string> getGray(int n) {
    // write code here
    vector<string> res;
    if (n == 1) {
        res.push_back("0");
        res.push_back("1");
        return res;
    }
    vector<string> v = getGray(n - 1);
    int len = pow(2, n - 1);
    for (int i = 0; i < len; i++) {
        res.push_back("0" + v[i]);
    }
    for (int i = len - 1; i >= 0; i--) {
        res.push_back("1" + v[i]);
    }
    return res;
}

//void test()
//{
// vector<string>res=getGray(3);
// for (int i = 0; i < res.size(); ++i)
// cout << res[i]<<endl;
//}

你可能感兴趣的:(腾讯笔试:>格雷码)