【发布时间】:2014-06-30 03:29:55
【问题描述】:
我有这个功能:
void permutate (const string & s, std::vector<int>& index, std::size_t depth, int & count)
{
if (depth == s.size())
{
++count;
for (std::size_t i = 0; i < s.size(); ++i)
{
cout << s[index[i]];
}
cout << "\n";
return;
}
for (std::size_t i = 0; i < s.size(); ++i)
{
index[depth] = i;
permutate(s, index, depth + 1, count);
}
}
要打印所有组合,我使用这个:
void print(string s) {
if (s.find_first_not_of(s.front()) == string::npos)
{
cout << "Only 1 combination exists";
return;
}
sort(s.begin(), s.end());
cout << s << "\n**********\n";
vector<int> index(s.size());
int count = 0;
permutate(s, index, 0, count);
cout << "\nTotal combinations with repetitions: " << count;
}
功能很好用,但我需要特定的组合。例如,如果我写
打印(“ABC”);
我得到:AAA、AAB、AAC、ABA、...、CCA、CCB、CCC。所以,我得到了 27 种组合。但是,如果我需要进行组合的大小不是原始集合之一(在这种情况下,原始集合的大小是 3)?
例如,如果我有一个字符串“ABC”(或一组 S = {A, B, C})并且我想要大小为 2 的组合,我应该得到正好 9 个组合:AA、AB、AC、BA , BB, BC, CA, CB, CC.
请提出为实现我的目标而应进行的更改。谢谢。
!!!编辑:
我想要与here 相同的结果,但在 C++ 中。【问题讨论】:
-
C++ 的优点在于它拥有的所有standard algorithms,就像generate permutations 的函数一样。
-
它不会产生重复排列,而且你不能指定想要排列的大小。
-
“AAA”不是“ABC”的排列...您正在寻找组合,而不是排列。
-
没错。谢谢。
-
请注意组合和排列的区别。在排列中,顺序很重要。但是在一个组合中,AAB 和 ABA 和 BAA 都是一样的。因此,这个问题的标题是错误的,应该说:Function to find all permutations with repeats.
标签: c++ set permutation