我正在编写一个算法来生成此类数组的所有可能排列:
n = 长度
k = 数组中 1 的个数
所以这意味着如果我们有 k 个 1,我们将在数组中有 n-k 个 0。
例如: n = 5; k = 3;
很明显,这个数组有 5 种选择 3 种可能的排列,因为
n!/(k!(n-k)!
5!/(3!2!) = (5*4)/2 = 10
数组的可能值
以下是所有值:
11100
11010
11001
10110
10101
10011
01110
01101
01011
00111
我猜我应该使用递归算法,但我只是没有看到它。我正在用 C++ 编写这个算法。
如有任何帮助,我们将不胜感激!
最佳答案
只需从 00111
开始,然后使用 std::next_permutation
生成其余部分:
#include <algorithm>
#include <iostream>
#include <string>
int main()
{
std::string s = "00111";
do
{
std::cout << s << '\n';
}
while (std::next_permutation(s.begin(), s.end()));
}
输出:
00111
01011
01101
01110
10011
10101
10110
11001
11010
11100
关于c++ - 排列所有可能的 (0, 1) 值数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3735170/