日期:2014-05-20  浏览次数:20807 次

有意思的题哦!
在m个数中求n个数的所有组合(n <m)!
怎么整?我都不知道怎么下手,哎,太菜了,高手指点啊

------解决方案--------------------
CSDN上都讨论过多次了。
------解决方案--------------------
主  题: 一个看似简单,可是越想越不知下手!
a[n][m]
当n=1;m=2;
(1)a[1][1]=x;
(2)a[1][2]=x

当n=2;m=2
(1){a[1][1]=x,a[2][1]=x};
(2){a[1][1]=x,a[1][2]=x};
(3){a[1][2]=x,a[2][1]=x};
(4){a[1][2]=x,a[2][2]=x}

当n=3;m=2
(1){a[1][1]=x,a[2][1]=x,a[3]a[1]=x};(2){a[1][1]=x,a[2][1]=x,a[3][2]=x;}
(3){a[1][1]=x,a[2][2]=x,a[3]a[1]=x};(4){a[1][1]=x,a[2][2]=x,a[3][2]=x;}
(5){a[1][2]=x,a[2][1]=x,a[3]a[1]=x};(6){a[1][2]=x,a[2][1]=x,a[3][2]=x;}
(7){a[1][2]=x,a[2][2]=x,a[3]a[2]=x};(8){a[1][2]=x,a[2][2]=x,a[3][2]=x;}

当n=4;m=2;
...................
当n=5;m=2
.....................
现假设M不变为2减少难度,N是可以改变的也就是有2^N的组合赋值方式请问这种算法
这样解决啊,这样编!
//如若你要对M^N个数据赋值,
//可以用一维数组来模拟多维数组。
//比如
//int a[2][2][2];
//你可以用 b[2*2*2]来代替,
//而使用的时候 a[1][0][1]就是b[1*2*2+0*2+1]

//举例:M=每维下标 N=维数

#define M 3
#define N 4

long* pData; // data[3][3][3][3]

#include <iostream>
#include <math.h>
//#include <stdio.h>
using namespace std;

int main()
{

char str[100];
char strtemp1[100];
char strtemp2[100];
int len=pow(M,N);
pData=new long[len];
int i;
for(i=0;i <len;i++)pData[i]=i;//赋值
//显示
for(i=0;i <len;i++)
{
int j;
int temp=i;
strcpy(str, " ");
strcpy(strtemp1, " ");
strcpy(strtemp2, " ");
for(j=0;j <N;j++)
{
itoa(temp%M,strtemp2,sizeof(strtemp2));
strcat(strtemp1, "[ ");
strcat(strtemp1,strtemp2);
strcat(strtemp1, "] ");
temp/=M;
strcat(strtemp1,str);
strcpy(str,strtemp1);
strcpy(strtemp1, " ");
}
strcpy(strtemp1, "\nData ");
strcat(strtemp1,str);
cout < <strtemp1 < < "= " < <pData[i];//数值
}
cout < <endl;
return 0;
}

运行结果


Data[0][0][0][0]=0
Data[0][0][0][1]=1
Data[0][0][0][2]=2
Data[0][0][1][0]=3
//省略
Data[2][2][2][0]=78
Data[2][2][2][1]=79
Data[2][2][2][2]=80


最后还应该
delete[] pData;
------解决方案--------------------
请问各位怎么发帖呀?