c++ - 在 C++ 中计算具有不同列数的数字的不同组合?

标签 c++ math boost statistics

如果有人能指出我解决这个问题的正确方向,我将不胜感激。我试图找到各种数字的所有不同组合,每个数字都有不同的列数(在 C++ 中)。例如考虑数字 2:

两列:

2 = { 2 , 0 } { 0 , 2 } { 1 , 1 }

三列:

2 = { 0 , 0 , 2 } { 0 , 2 , 0 } { 2 , 0 , 0 } { 1 , 1 , 0 } { 0 , 1 , 1 } { 1 , 0 , 1 }

四列:

2 = { 0 , 0 , 0 , 2 } { 0 , 0 , 2 , 0 } { 0 , 2 , 0 , 0 } { 2 , 0 , 0 , 0 } { 1 , 1 , 0 , 0 } { 0 , 0 , 1 , 1 } { 0 , 1 , 1 , 0 } { 1 , 0 , 0 , 1 } { 1 , 0 , 1 , 0 } { 0 , 1 , 0 , 1 }

提前致谢!

最佳答案

这是我的尝试:

void combinations(int n, int columns, std::vector<int>& soFar)
{
    if (columns == 1)
    {
        for (auto e : soFar)
            std::cout << e << " ";
        std::cout << n << '\n';
        return;
    }

    for (int i = 0; i <= n; ++i)
    {
        soFar.push_back(i);
        combinations(n - i, columns - 1, soFar);
        soFar.pop_back();
    }
}

void combinations(int n, int columns)
{
    std::vector<int> soFar;
    combinations(n, columns, soFar);
}

基本上,您一直将数字分成两个子部分,直到达到深度限制(您的情况下的列数)。
为了在备份过程中继续打印之前的数字,我将它们存储在 soFar vector 中,并相应地推送和弹出它们。

这是 combinations(2, 4) 的输出:

0 0 0 2
0 0 1 1
0 0 2 0
0 1 0 1
0 1 1 0
0 2 0 0
1 0 0 1
1 0 1 0
1 1 0 0
2 0 0 0

关于c++ - 在 C++ 中计算具有不同列数的数字的不同组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19337228/

相关文章:

c++ - 如何通过R-最近邻来求解最近邻?

performance - 假设需要 f(n) 微秒,一秒内可解决的最大难题是什么?

3 个数字的 Javascript max() 函数

c++ - 在将字符串转换为 ptime 时使用 %f 标志 boost ptime input_facet 错误

c++ - Rubik's Cube Scramble 生成器算法

c++ - 如果我删除 C++ 程序正在向其写入数据的文件,会发生什么情况?

c++ - boost 目录迭代器抛出 ERROR_INVALID_DRIVE

c++ - 使用自定义编译的 zlib 在 Linux 上编译 Boost.Iostream 会导致多个卡纸错误

c# - 通过代码获取文件 tnsnames.ora 的位置

java - opencv和python——激光曲线检测