【发布时间】:2015-12-30 01:25:14
【问题描述】:
我想构建一个 C++ 程序,根据 N 因子所采用的元素数量显示所有可能的组合。
让我们假设一个向量 vec[6] 上面有元素 1 2 3 4 5 6。
使用组合公式,6! /4! (6 - 4)! = 15 种可能性
我想生成一个函数,它给出所有 15 种可能性的结果,4 乘 4 不重复,例如:
1 2 3 4
1 2 3 5
1 2 3 6
2 3 4 5
等等……
我现在正在使用此代码,但我想使用矢量 (v[6]) 中的数字。
#include <algorithm>
#include <iostream>
#include <string>
void comb(int N, int K)
{
std::string bitmask(K, 1); // K leading 1's
bitmask.resize(N, 0); // N-K trailing 0's
// print integers and permute bitmask
do {
for (int i = 0; i < N; ++i) // [0..N-1] integers
{
if (bitmask[i]) std::cout << " " << i;
}
std::cout << std::endl;
} while (std::prev_permutation(bitmask.begin(), bitmask.end()));
}
int main()
{
comb(6, 4);
}
请大家帮帮我好吗?我想知道我可以在哪里更改代码,以便我可以使用自己的向量。
我正在生成这个向量 v[i] 并使用冒泡排序对其进行排序,如下所示:
void order (int d[], int n){
int i, j;
for (i = 1; i < n; i++)
for (j = 0; j < n-1; j++)
if (d[j] > d[j+1])
swap (d[j],d[j+1]);
for (i = 0; i < n; i++)
cout << d[i] << " ";
}
在排序之后,我想将我的向量放入梳子函数中。 我怎样才能使它成为可能?
【问题讨论】:
-
用
std::cout << " " << v[i]替换std::cout << " " << i? -
我的意图是让一个函数传递一个数字向量而不是数字,就像这样:void order(int d[], int K){}
标签: c++ combinations combinatorics