[英]Backtracking algorithm to generate all combinations
I have a little problem with this.I want to generate every possible combination.The numbers located in 1D array and it is read from a file. 我对此有一点问题,我想生成每种可能的组合。位于1D数组中的数字是从文件中读取的。 Now I don't know the problem: I know that every combination which will be printed to monitor is in ascending order.
现在我不知道问题所在:我知道将打印到监视器的每个组合都是按升序排列的。 The probelm is that if it finishes with smallest number it doesn't ascends to the next number.
问题是,如果它以最小的数字结尾,则不会上升到下一个数字。
Example: The 1D array file with 1,2,3,4,5 and n = 5 and p = 3; 示例:一维数组文件,其中1,2,3,4,5且n = 5且p = 3; Possible combinations:
可能的组合:
1 2 3, 1 2 4, 1 2 5, 1 3 4, 1 3 5, 1 4 5, 2 3 4, 2 3 5, etc... 1 2 3,1 2 4,1 2 5,1 3 4,1 3 5,1 4 5,2 3 4,4 3 5等
Here is what I done so far: 这是我到目前为止所做的:
#include <stdio.h>
#include <stdlib.h>
void print(int*,int);
void combination(int*,int,int,int);
int main()
{
FILE *fin = fopen("bemenet.txt","r");
if(!fin){printf("Error opening file @!!!");return 0;}
int *a,i,n,p = 3;
fscanf(fin,"%i ",&n);
a = (int*)malloc(n*sizeof(int));
for(i = 0; i < n; ++i){
fscanf(fin,"%i ",&a[i]);
}
combination(a,n,p,0);
return 0;
}
void combination(int *a,int n,int p,int k)
{
int i;
if(k == p){
print(a,k);
}
else{
for(a[k + 1] = a[k] + 1 ; a[k+1] < n; ++a[k+1]){
combination(a,n,p,k+1);
}
}
}
void print(int *a,int k)
{
int i;
for(i = 0; i < k; ++i){
printf("%i ",a[i]);
}
printf("\n");
}
The reason why the number are only incrementing is, that you never decrement them. 数字仅递增的原因是,您永不递减。 Also the condition
a[k+1] < n
doesn't make any sense to me, why would you compare a size of the field to the element of the array (which can be eg 1000)? 另外条件
a[k+1] < n
对我没有任何意义,为什么还要将字段的大小与数组的元素进行比较(例如可以为1000)? Also you should't be changing the elements in the array as ++a[k+1]
since there is no reason to do so. 另外,您也不应将数组中的元素更改为
++a[k+1]
因为没有理由这样做。
See for example Algorithm to generate all possible permutations of a list? 参见例如生成列表的所有可能排列的算法? for more help.
寻求更多帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.