简体   繁体   中英

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. 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; 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...

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)? Also you should't be changing the elements in the array as ++a[k+1] since there is no reason to do so.

See for example Algorithm to generate all possible permutations of a list? for more help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM