排列和组合生成算法
Permutations & combination generating algorithm
我想写下一种算法来打印出给定的'<>'对的所有可能组合,我试图开发一种算法来解决这个问题,但我认为这是不正确的,因为我确实意识到这个问题与排列有关 [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);
}
///输出
((((()))))
(((()())))
(((())()))
(((()))())
(((())))()
((()(())))
((()()()))
((()())())
((()()))()
((())(()))
((())()())
((())())()
((()))(())
((()))()()
(()((())))
(()(()()))
(()(())())
(()(()))()
(()()(()))
(()()()())
(()()())()
(()())(())
(()())()()
(())((()))
(())(()())
(())(())()
(())()(())
(())()()()
()(((())))
()((()()))
()((())())
()((()))()
()(()(()))
()(()()())
()(()())()
()(())(())
()(())()()
()()((()))
()()(()())
()()(())()
()()()(())
()()()()()
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 计算数组重复次数的组合的有效算法,加起来达到给定的总和
- 为 C++11 算法组合多个谓词
- 双重释放或损坏(输出):使用向量的组合算法0x0000000001a880a0***
- Python到C++:使用递归列出背包的所有组合的算法
- 从给定的 IPv6:端口列表中搜索 IPv6:端口组合的最快搜索算法是什么 O(1) 时间一致性
- 给定数字与重复的组合的算法?C
- 排列和组合生成算法
- 加密++对称算法和经过身份验证的块模式组合
- 所有的组合算法和解决C++问题的一般方法
- 按字典顺序打印给定字符串的所有字母组合的算法
- 生成每个可能的 7 位数字组合的算法
- 运行整数数组所有组合的算法
- 根据组合框中的选定项目选择算法
- C++算法优化:从N个元素中求出K组合
- 递归算法将所有组合分成两组
- 数组算法的组合
- 按类型算法的列表组合
- 一个很好的算法来获得元素的闲置组合
- 是硬币变化算法,输出仍可由DP解决的所有组合