gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:47:56 25 4
gpt4 key购买 nike

如果有人能指出我解决这个问题的正确方向,我将不胜感激。我试图找到各种数字的所有不同组合,每个数字都有不同的列数(在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com