排列和组合生成算法

Permutations & combination generating algorithm

本文关键字:算法 组合 排列      更新时间:2023-10-16

我想写下一种算法来打印出给定的'<>'对的所有可能组合,我试图开发一种算法来解决这个问题,但我认为这是不正确的,因为我确实意识到这个问题与排列有关 [nPr],假设对于给定的输入 5,它应该创建 120 个组合 (5P5=120),但我的代码只生成 81。

In my code have tried to generate all possible combinations by placing every element at every place one by one, but now I am little confused about how correct this approach is?

事情是 很可能我无法掌握"制作子集/组合/排列"的真正概念(尽管理论上我知道它们是什么以及如何计算它们)

我不是在寻找一个完整的最终"勺子喂食代码",而是可以解释我"我应该做什么"的东西,我可以从中提取步骤,理解概念并开发自己的步骤。

If possible something extending or tweaking my current coding to achieve the right result would be easier for me to understand.

void permute()
{
string str=”<><><>”;
char buck=' ';
for(int a=0;a<str.length()-1;a++)
{
for(int b=0;b<str.length()-1;b++){
cout<<str<<endl;
buck=str[b];
str[b]=str[b+1];
str[b+1]=buck;
}
}
}

我一直在努力了解我应该做什么,但我仍在挣扎,任何帮助或指导都会非常有帮助。 谢谢


From 'all combinations' i mean printing out all the possible ways given set of characters can be arranged, lets say for 2 pairs '<><>' it should be like: <><>,><<>,><<>,><><,<<>>,>><< ... ... ...

C++提供了将(第一个,最后一个)的内容修改为序列中的下一个排列的bool std::next_permutation(Iterator first, Iterator last),如果有更多排列,则返回true,如果这是最后一个排列,则返回false。列表需要首先排序(使用std::sort(Iterator first, Iterator last)),排序列表形成第一个排列。

您可以使用str.begin()str.end()与这些算法进行交互。

注意:由于您的数据集包含重复的项目,因此并非所有排列都是可能的(有些将是其他条目的重复项)。那是:

string : permutations
-------:-------------
abcd   : 24
<><>   : 6
abcdef : 720
<><><> : 20

如果你真的想要所有的排列(包括重复),你可以有一个int indices = { 0, 1, 2, 3, 4, 5 };数组,你运行排列,然后为每个排列打印str[indices[0]]str[indices[5]]

这可以让您深入了解您的算法以及出了什么问题。也就是说,它可以作为比较您的算法的参考。

根据我的测试,它有 42 个解决方案:

function placeBrackets(n)
{
var placeBracketsRecur = function(prefix, remainingOpen, remainingClosed)
{
if(remainingClosed == 0)
{
document.write(prefix + "<br/>");
return;
}
if(remainingOpen > 0)
{
placeBracketsRecur(prefix + "(",  remainingOpen - 1, remainingClosed);
}
if(remainingOpen < remainingClosed)
{
placeBracketsRecur(prefix + ")",  remainingOpen, remainingClosed - 1);
}
}
placeBracketsRecur("", n, n);
}

///输出

((((()))))
(((()())))
(((())()))
(((()))())
(((())))()
((()(())))
((()()()))
((()())())
((()()))()
((())(()))
((())()())
((())())()
((()))(())
((()))()()
(()((())))
(()(()()))
(()(())())
(()(()))()
(()()(()))
(()()()())
(()()())()
(()())(())
(()())()()
(())((()))
(())(()())
(())(())()
(())()(())
(())()()()
()(((())))
()((()()))
()((())())
()((()))()
()(()(()))
()(()()())
()(()())()
()(())(())
()(())()()
()()((()))
()()(()())
()()(())()
()()()(())
()()()()()