栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

生成给定长度的所有可能的一和零的数组的算法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

生成给定长度的所有可能的一和零的数组的算法

您将如何在纸上手动计数?您将检查最后一位数字。如果为0,则将其设置为1。如果已经为1,则将其设置回0,然后继续下一个数字。因此,这是一个递归过程。

以下程序通过更改序列来生成所有可能的组合:

#include <iostream>template <typename Iter>bool next(Iter begin, Iter end){    if (begin == end)      // changed all digits    {// so we are back to zero        return false;      // that was the last number    }    --end;    if ((*end & 1) == 0)   // even number is treated as zero    {        ++*end; // increase to one        return true;       // still more numbers to come    }    else        // odd number is treated as one    {        --*end; // decrease to zero        return next(begin, end);   // RECURSE!    }}int main(){    char test[] = "0000";    do    {        std::cout << test << std::endl;    } while (next(test + 0, test + 4));}

该程序适用于任何类型的任何序列。如果您同时需要所有可能的组合,只需将它们放入集合中,而不是打印出来。当然,您需要其他元素类型,因为您不能将C数组放入向量中。让我们使用字符串向量:

#include <string>#include <vector>int main(){    std::vector<std::string> combinations;    std::string test = "0000";    do    {        combinations.push_back(test);    } while (next(test.begin(), test.end()));    // now the vector contains all pssible combinations}

如果您不喜欢递归,这里有一个等效的迭代解决方案:

template <typename Iter>bool next(Iter begin, Iter end){    while (begin != end)       // we're not done yet    {        --end;        if ((*end & 1) == 0)   // even number is treated as zero        { ++*end; // increase to one return true;       // still more numbers to come        }        else        // odd number is treated as one        { --*end; // decrease to zero and loop        }    }    return false;   // that was the last number}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637530.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号