求排列函数的写法

gths123 2008-08-03 03:17:44
想写一个函数计算n个数里面取m个的排列An(m),函数原型如下:
void permutate(int[] source,int[][] permutated,int n,int m);
我想到的思路就是根据公式,先求出n个数里面m个数的组合,然后对每一个组合求全排列。但是觉得这样做不是最好的方法,想问各位高手有没有更好的方案。最好是能给出源代码。谢谢
...全文
199 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
chenhjcs 2008-08-04
  • 打赏
  • 举报
回复
排列还是建议使用STL
hongyzniu 2008-08-03
  • 打赏
  • 举报
回复
http://blog.csdn.net/solstice/archive/2002/10/21/2059.aspx
hongyzniu 2008-08-03
  • 打赏
  • 举报
回复
//STL就是好啊,next_permutation可以计算一组数据的全排列

// next_permutation
#i nclude <iostream>
#i nclude <algorithm>
using namespace std;

int main () {
int myints[] = {1,2,3};

cout << "The 3! possible permutations with 3 elements:\n";

sort (myints,myints+3);

do {
cout << myints[0] << " " << myints[1] << " " << myints[2] << endl;
} while ( next_permutation (myints,myints+3) );

return 0;
}
wjb_yd 2008-08-03
  • 打赏
  • 举报
回复
不好意思,看错了,您要的是排列,我说的是组合
wjb_yd 2008-08-03
  • 打赏
  • 举报
回复
动态规划
c(n,m)=c(n-1,m)+c(n-1,m-1)
gths123 2008-08-03
  • 打赏
  • 举报
回复
顶一下吧
gfcs19840222 2008-08-03
  • 打赏
  • 举报
回复
你这个只是求组合的算法。没有对每个组合做全排列。
gfcs19840222 2008-08-03
  • 打赏
  • 举报
回复
你这个只是求排列的算法。没有对每个组合做全排列。
gfcs19840222 2008-08-03
  • 打赏
  • 举报
回复
其实只要把全排列的算法改一改就可以了。

下面是我在网上找到的全排列代码

http://www.cnblogs.com/nokiaguy/archive/2008/05/11/1191914.html
#include <stdio.h>

int n = 0;

void swap(int *a, int *b)
{
int m;
m = *a;
*a = *b;
*b = m;
}
void perm(int list[], int k, int m)
{
int i;
if(k > m)
{
for(i = 0; i <= m; i++)
printf("%d ", list[i]);
printf("\n");
n++;
}
else
{
for(i = k; i <= m; i++)
{
swap(&list[k], &list[i]);
perm(list, k + 1, m);
swap(&list[k], &list[i]);
}
}
}
int main()
{
int list[] = {1, 2, 3, 4, 5};
perm(list, 0, 4);
printf("total:%d\n", n);
return 0;
}


如果有N个数,从中取T个数
只要将perm函数中的if(k>m)改成if(m-k+1== N-T)
然后list的前T个元素即为所求。


另外,你的函数接口有点问题,因为你的答案将有N!/(N-T)!个,存不下来的。
ndsl3334 2008-08-03
  • 打赏
  • 举报
回复

#include <iostream>
using namespace std;

int a[100];

void comb(int m,int k)
{
int i,j;
for (i=m;i>=k;i--) {
a[k]=i;
if (k>1)
comb(i-1,k-1);
else
{
for (j=a[0];j>0;j--)
cout << a[j];
cout << endl;
}
}
}

void main()
{
a[0]=3;
comb(5,3);
}


64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧