请看下面的代码:
运行这段代码会得到以下输出结果:
请注意,这段代码并没有实现其所声称要做的事情!它不是返回给定子集大小的所有组合重复的目标,而是返回给定子集大小的所有重复排列。当然,获得组合的方法是生成我所做的所有排列,然后循环遍历以除去那些彼此排列的排列之一。但我相信这绝对不是最有效的方法。
我看到过使用嵌套的for循环来实现这个的方法,但那些方法假设子集大小预先知道。我正在尝试为任何子集大小进行泛化,这就是为什么我试图递归地完成它的原因。问题在于,我不确定我需要如何更改我的递归“helpfunc”才能以有效的方式生成所有组合。
仅澄清一下,预期输出将是这样的:
#include <vector>
#include <iostream>
#include <string>
template <typename T>
void print_2d_vector(std::vector<std::vector<T>>& v)
{
for(int i = 0; i < v.size(); i++)
{
std::cout << "{";
for(int j = 0; j < v[i].size(); j++)
{
std::cout << v[i][j];
if(j != v[i].size() - 1)
{
std::cout << ", ";
}
}
std::cout << "}\n";
}
}
template <typename T>
struct permcomb2
{
std::vector<std::vector<T>> end_set;
std::vector<T>* data;
permcomb2(std::vector<T>& param) : data(¶m) {}
void helpfunc(std::vector<T>& seen, int depth)
{
if(depth == 0)
{
end_set.push_back(seen);
}
else
{
for(int i = 0; i < (*data).size(); i++)
{
seen.push_back((*data)[i]);
helpfunc(seen, depth - 1);
seen.pop_back();
}
}
}
};
template <typename T>
std::vector<std::vector<T>> permtest(std::vector<T>& data, int subset_size)
{
permcomb2<T> helpstruct(data);
std::vector<T> empty {};
helpstruct.helpfunc(empty, subset_size);
return helpstruct.end_set;
}
using namespace std;
int main()
{
std::vector<std::string> flavors {"Vanilla", "Chocolate", "Strawberry"};
auto a1 = permtest(flavors, 2);
cout << "Return all combinations with repetition\n";
print_2d_vector(a1);
return 0;
}
运行这段代码会得到以下输出结果:
Return all combinations with repetition
{Vanilla, Vanilla}
{Vanilla, Chocolate}
{Vanilla, Strawberry}
{Chocolate, Vanilla}
{Chocolate, Chocolate}
{Chocolate, Strawberry}
{Strawberry, Vanilla}
{Strawberry, Chocolate}
{Strawberry, Strawberry}
请注意,这段代码并没有实现其所声称要做的事情!它不是返回给定子集大小的所有组合重复的目标,而是返回给定子集大小的所有重复排列。当然,获得组合的方法是生成我所做的所有排列,然后循环遍历以除去那些彼此排列的排列之一。但我相信这绝对不是最有效的方法。
我看到过使用嵌套的for循环来实现这个的方法,但那些方法假设子集大小预先知道。我正在尝试为任何子集大小进行泛化,这就是为什么我试图递归地完成它的原因。问题在于,我不确定我需要如何更改我的递归“helpfunc”才能以有效的方式生成所有组合。
仅澄清一下,预期输出将是这样的:
Return all combinations with repetition
{Vanilla, Vanilla}
{Vanilla, Chocolate}
{Vanilla, Strawberry}
{Chocolate, Chocolate}
{Chocolate, Strawberry}
{Strawberry, Strawberry}
那么,我该如何更改我的代码,以便以高效的方式获取所有带重复的组合,而不是排列?
for( int i = 0; i < 10; ++i ) for( int j = i; j < 10; ++j ) { cout << i << ", " << j << endl; }
- Cheers and hth. - Alfsubset_size = 2
。 - Jon Deaton