Print k-element subsets of an n
element set (In essence n choose k)
represent each subset as an array and skip B[0]
.
For example [0 1 0 1] means {1,3} to print.
I believe my main problem is in my printSubsets()
function because I am calling the method twice.
But it looks like it can't do that; it ignores the "2" in the index until the very end of the program.
Code
#include <stdio.h>
#include <stdlib.h>
void printSet(int B[], int n) {
for(int j = 1; j <= n; j++) {
printf("%d", B[j]);
}
}
void printSubsets(int B[], int n, int k, int i) {
if(i <= n) {
if(k == 0) {
printSet(B, n);
printf("\n");
}else{
B[i] = 1; //print 1 in the index of interest and recurse
printSubsets(B, n, k-1, i++);
B[i] = 2; //print 2 as a holder to ignore that index
printSubsets(B, n, k, i++);
}
}
}
int main(){
int n;
int k;
scanf("%d %d", &n, &k);
int B[101];
printSubsets(B, n, k, 1);
return EXIT_SUCCESS;
}