• 利用递归算法生成格雷码


    利用递归算法生成格雷码

    #include <iostream>

    #include <string>

    #include <stack>

    #include <stdlib.h>

    std::stack<std::string> result;

    static int count;

    void generator() {

    count--;

    if (count > 0) {

    generator();

    std::stack<std::string> newResult;

    int c = 0;

    while(!result.empty()) {

    std::string newA, newB;

    newA = result.top();

    result.pop();

    if (!c) {

    newB = newA + "0";

    newResult.push(newB);

    newB = newA + "1";

    newResult.push(newB);

    c = 1;

    } else {

    newB = newA + "1";

    newResult.push(newB);

    newB = newA + "0";

    newResult.push(newB);

    c = 0;

    }

    }

    if (count % 2 == 0) {

    while(!newResult.empty()) {

    result.push(newResult.top());

    newResult.pop();

    }

    } else

    result = newResult;

    } else {

    result.push("1");

    result.push("0");

    }

    }

    int main() {

    std::cin >> count;

    generator();

    while(!result.empty()) {

    std::cout << result.top() << std::endl;

    result.pop();

    }

    return 0;

    }

     

  • 相关阅读:
    JUC并发工具包之Semaphore
    Linux命令
    uWSGI
    数据库 MySQL 练习
    c++
    c++ 初阶
    Git
    MySQl 和 Redis
    MySQL 查询
    MySQL 命令
  • 原文地址:https://www.cnblogs.com/Anei/p/7805609.html
Copyright © 2020-2023  润新知