Permutation(排列组合)
排列问题:
设R = {r1, r2, … , rn}是要进行排列的n个元素, Ri = R-{ri}; 集合X中元素的全排列记为Permutation(X), (ri)Permutation(X)表示在全排列Permutation(X)的每个排列前加上前缀ri得到的排列.
R的全排列可归纳定义以下:
当n=1时,Permutation(R)={r},r是集合R中唯1的元素;
当n>1时,Permutation(R)由(r1)Permutation(R1),(r2)Permutation(R2), …, (rn)Permutation(Rn)构成。
顺次递归定义,则可设计产生Permutation(X)的递归算法以下:
void permutation(Type *array, int front, int last)
{
//已递归到了最后1个元素
if (front == last)
{
//打印输出
for (int i = 0; i < front; ++i)
{
cout << array[i] << ‘ ‘;
}
cout << array[front] << endl;
return ;
}
else
{
for (int i = front; i <= last; ++i)
{
// 不断的从下标为[front ~ last]的元素当选择1个元素
//作为当前序列的开头元素
std::swap(array[front], array[i]);
permutation(array, front+1, last);
std::swap(array[front], array[i]);
}
}
}
算法说明:
算法Permutation(array, k, m)递归地产生所有前缀是array[0:k⑴],且后缀是array[k:m]的全排列的所有排列.函数调用(list, 0, n⑴)则产生list[0:n⑴]的全排列.
算法演示:
char str[] = “abc”;的递归调用进程如图:
小结:
虽然我们自己实现了Permutation, 但C++ STL中也实现了std::next_permutation算法, 在1般利用中, 我比较推荐使用STL中已实现好的next_permutation, 毕竟STL的代码质量还是非常高的, 而且速度1点也不逊色于我们的实现;
插入排序
插入排序是低级排序中速度最快的1种(冒泡/选择/插入排序效力均为O(N^2)),但是跟快速排序(NlogN),归并排序(NlogN)还是有1定的差距的⊙
波比源码 » 数据结构基础(3) –Permutation & 插入排序
Thank you for great content. Hello Administ. Onwin , Onwin Giriş , Onwin Güncel Giriş , Onwin Yeni Adres , onwin
Hackdra’s smart contract auditing service ensures that decentralized applications and smart contracts are free of vulnerabilities and security loopholes. Request free smart contract audit now.