我想编写一个函数来从n元素的列表中选择k元素的组合。我有我以pdf格式转换为文本的给定源文件。并且我得到了以下列表。我试图使用dfs
找到组合,但有约束,需要先管理,它令我困惑。我们需要从下面的列表中选择3个主题。在下面的行/
意味着这些科目中的任何一个,如Ex.from a)History or Sociology or Economics
应该被选中。约束条件是数学不能与孟加拉语或印地语任何组合。 一些有效的组合是算法,从n个元素的列表中寻找组合
History,Bengali,Sanskrit
Bengali,Philosophy,English
列表的快照 -
a) History/Sociology/Economics
b) Bengali/Hindi
c) Sanskrit/Mathematics
d) Philosophy
e) Political Science
f) English
共有3科目组合会像(6C3*3*2*2)-24
(从我的计算) 我想到了一个办法来表示列表,以便我可以有效地编码它。但不能找出一个合理的方法来解决这个问题。 这是我实现
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int counter=0;
void combination(char *p[10],char *d[10],int start,int end,int index,int r){
int i,j,k=0;
// char ch[10]="History";
if(index==r){
if(!strcmp(d[0],"History")){
if(!strcmp(d[1],"Sociology") || !strcmp(d[1],"Economics") || !strcmp(d[2],"Sociology") || !strcmp(d[2],"Economics"))
return;
}
if(!strcmp(d[0],"Sociology")){
if(!strcmp(d[1],"History") || !strcmp(d[1],"Economics") || !strcmp(d[2],"History") || !strcmp(d[2],"Economics"))
return;
}
if(!strcmp(d[0],"Economics")){
if(!strcmp(d[1],"History") || !strcmp(d[1],"Sociology") || !strcmp(d[2],"History") || !strcmp(d[2],"Sociology"))
return;
}
if(!strcmp(d[0],"Bengali")){
if(!strcmp(d[1],"Hindi") || !strcmp(d[2],"Hindi") || !strcmp(d[1],"Mathematics") || !strcmp(d[2],"Mathematics"))
return;
}
if(!strcmp(d[0],"Hindi")){
if(!strcmp(d[1],"Bengali") || !strcmp(d[2],"Bengali") || !strcmp(d[1],"Mathematics") || !strcmp(d[2],"Mathematics"))
return;
}
if(!strcmp(d[0],"Sanskrit")){
if(!strcmp(d[1],"Mathematics") || !strcmp(d[2],"Mathematics"))
return;
}
if(!strcmp(d[0],"Mathematics")){
if(!strcmp(d[1],"Sanskrit") || !strcmp(d[2],"Sanskrit") || !strcmp(d[1],"Bengali") || !strcmp(d[2],"Bengali") || !strcmp(d[1],"Hindi") || !strcmp(d[2],"Hindi"))
return;
}
if(!strcmp(d[1],"Mathematics")){
if(!strcmp(d[2],"Bengali") || !strcmp(d[2],"Hindi"))
return;
}
if(!strcmp(d[2],"Mathematics")){
if(!strcmp(d[1],"Bengali") || !strcmp(d[1],"Hindi"))
return;
}
for(j=0;j<r;j++)
printf("%s ",d[j]);
counter++;
printf("\n");
return;
}
for(i=start;i<=end && end-i+1>=r-index; i++){
d[index]=p[i];
combination(p,d,i+1,end,index+1,r);
}
}
int main(){
char *subject[10],n[50],*p,*data[10];
int len,i,m;
printf("\nEnter the no subject\n");
scanf("%d",&m);
printf("\nEnter name of subject\n");
for(i=0;i<m;i++){
scanf("%s",n);
len=strlen(n);
p=(char *)malloc(len+1);
strcpy(p,n);
subject[i]=p;
}
combination(subject,data,0,m-1,0,3);
printf("\nCount=%d\n",counter);
return 0;
}
如果什么列表是挺大那么如何处理其输出会更加大,那么复杂性将增加,最终会失败 有没有解决这个任何优雅的方式与任何语言的预定义的语言数据结构
该解决方案将根据不同的语言非常不同。请选择一个,我推荐你写下你的尝试。你有*试图自己解决它? –
1)哪种语言? 2)你到目前为止尝试过什么?我们在这里不做家庭作业。 – holgac
这是来自我正在从事的一个项目,有这样一个列表,我必须检查它是否有效的选择基于列表总可能的组合@holgac – Xax